feat(stdlib): Mid M3 hash digests and secure tokens

Add lib/hash and lib/secrets (EN/ZH) with known-vector golds,
getrandom-backed tokens, and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-07 20:15:36 +08:00
1 parent 94ae6713aa
commit 08384c7540
25 files changed
+489 -17

No files matched your search

+39 -1
View File
@@ -2,7 +2,9 @@
use std::collections::HashMap;
use crate::host::{encoding, fs, json, math, net, path, re, sys, time, writeback, HostContext};
use crate::host::{
encoding, fs, hash, json, math, net, path, re, secrets, sys, time, writeback, HostContext,
};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
#[cfg(feature = "plugin-host")]
@@ -147,6 +149,12 @@ pub enum HostFn {
FsCopyFile = 141,
FsMove = 142,
FsMakeTemp = 143,
HashSha256 = 144,
HashSha1 = 145,
HashMd5 = 146,
HashHmacSha256 = 147,
SecretsTokenHex = 148,
SecretsTokenUrlsafe = 149,
}
@@ -287,6 +295,12 @@ impl HostFn {
141 => Self::FsCopyFile,
142 => Self::FsMove,
143 => Self::FsMakeTemp,
144 => Self::HashSha256,
145 => Self::HashSha1,
146 => Self::HashMd5,
147 => Self::HashHmacSha256,
148 => Self::SecretsTokenHex,
149 => Self::SecretsTokenUrlsafe,
_ => return None,
})
}
@@ -430,6 +444,12 @@ impl HostFn {
"host_copy_file" | "copy_file" => Self::FsCopyFile,
"host_move" | "move_path" => Self::FsMove,
"host_make_temp" | "make_temp" => Self::FsMakeTemp,
"host_hash_sha256" | "hash_sha256" => Self::HashSha256,
"host_hash_sha1" | "hash_sha1" => Self::HashSha1,
"host_hash_md5" | "hash_md5" => Self::HashMd5,
"host_hash_hmac_sha256" | "hash_hmac_sha256" => Self::HashHmacSha256,
"host_secrets_token_hex" | "secrets_token_hex" => Self::SecretsTokenHex,
"host_secrets_token_urlsafe" | "secrets_token_urlsafe" => Self::SecretsTokenUrlsafe,
_ => return None,
})
}
@@ -560,6 +580,12 @@ impl HostFn {
Self::FsCopyFile => "host_copy_file",
Self::FsMove => "host_move",
Self::FsMakeTemp => "host_make_temp",
Self::HashSha256 => "host_hash_sha256",
Self::HashSha1 => "host_hash_sha1",
Self::HashMd5 => "host_hash_md5",
Self::HashHmacSha256 => "host_hash_hmac_sha256",
Self::SecretsTokenHex => "host_secrets_token_hex",
Self::SecretsTokenUrlsafe => "host_secrets_token_urlsafe",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -662,6 +688,9 @@ impl HostFn {
| Self::PathIsAbsolute => &["path"],
Self::FsCopyFile | Self::FsMove => &["src", "dest"],
Self::FsMakeTemp => &[],
Self::HashSha256 | Self::HashSha1 | Self::HashMd5 => &["text"],
Self::HashHmacSha256 => &["key", "text"],
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &[],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -696,6 +725,7 @@ impl HostFn {
Self::ListSlice => &["end"],
Self::ReReplace => &["count"],
Self::FsMakeTemp => &["prefix"],
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &["n"],
_ => &[],
}
}
@@ -1091,6 +1121,14 @@ pub fn call_host(
}
HostFn::FsMove => fs::move_path(ctx, require(bound, "src")?, require(bound, "dest")?),
HostFn::FsMakeTemp => fs::make_temp(ctx, bound.get("prefix")),
HostFn::HashSha256 => hash::sha256(require(bound, "text")?),
HostFn::HashSha1 => hash::sha1(require(bound, "text")?),
HostFn::HashMd5 => hash::md5(require(bound, "text")?),
HostFn::HashHmacSha256 => {
hash::hmac_sha256(require(bound, "key")?, require(bound, "text")?)
}
HostFn::SecretsTokenHex => secrets::token_hex(bound.get("n")),
HostFn::SecretsTokenUrlsafe => secrets::token_urlsafe(bound.get("n")),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
+67
View File
@@ -0,0 +1,67 @@
//! Digest / HMAC host primitives for Mid M3 (`lib/hash`).
use hmac::{Hmac, Mac};
use md5::Md5;
use sha1::Sha1;
use sha2::{Digest, Sha256};
use crate::value::Value;
type HmacSha256 = Hmac<Sha256>;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} needs text")),
}
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn sha256(text: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let mut h = Sha256::new();
h.update(t.as_bytes());
Ok(Value::Text(to_hex(&h.finalize())))
}
pub fn sha1(text: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let mut h = Sha1::new();
h.update(t.as_bytes());
Ok(Value::Text(to_hex(&h.finalize())))
}
pub fn md5(text: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let mut h = Md5::new();
h.update(t.as_bytes());
Ok(Value::Text(to_hex(&h.finalize())))
}
pub fn hmac_sha256(key: &Value, text: &Value) -> Result<Value, String> {
let k = as_text(key, "key")?;
let t = as_text(text, "text")?;
let mut mac =
HmacSha256::new_from_slice(k.as_bytes()).map_err(|e| format!("hmac_sha256: {e}"))?;
mac.update(t.as_bytes());
Ok(Value::Text(to_hex(&mac.finalize().into_bytes())))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha256_empty() {
let v = sha256(&Value::Text("".into())).unwrap();
assert_eq!(
v,
Value::Text(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".into()
)
);
}
}
+2
View File
@@ -12,11 +12,13 @@ pub mod event_bus;
#[cfg(feature = "exec-host")]
pub mod foreign;
mod fs;
mod hash;
pub(crate) mod json;
pub mod math;
mod net;
mod path;
mod re;
mod secrets;
#[cfg(feature = "plugin-host")]
pub mod plugin;
#[cfg(not(feature = "plugin-host"))]
+77
View File
@@ -0,0 +1,77 @@
//! Cryptographic token helpers for Mid M3 (`lib/secrets`).
use crate::value::Value;
fn nbytes(n: Option<&Value>) -> Result<usize, String> {
match n {
None | Some(Value::None) => Ok(16),
Some(Value::Int(i)) => {
if *i <= 0 {
return Err("n must be positive".into());
}
if *i > 1024 {
return Err("n too large (max 1024)".into());
}
Ok(*i as usize)
}
Some(_) => Err("n needs int".into()),
}
}
fn fill_random(buf: &mut [u8]) -> Result<(), String> {
getrandom::getrandom(buf).map_err(|e| format!("secrets: getrandom failed: {e}"))
}
pub fn token_hex(n: Option<&Value>) -> Result<Value, String> {
let len = nbytes(n)?;
let mut buf = vec![0u8; len];
fill_random(&mut buf)?;
Ok(Value::Text(
buf.iter().map(|b| format!("{b:02x}")).collect(),
))
}
const URLSAFE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
pub fn token_urlsafe(n: Option<&Value>) -> Result<Value, String> {
let len = nbytes(n)?;
let mut buf = vec![0u8; len];
fill_random(&mut buf)?;
// URL-safe Base64 without padding.
let mut out = String::with_capacity((len + 2) / 3 * 4);
let mut i = 0;
while i + 3 <= buf.len() {
let n = ((buf[i] as u32) << 16) | ((buf[i + 1] as u32) << 8) | (buf[i + 2] as u32);
out.push(URLSAFE[((n >> 18) & 63) as usize] as char);
out.push(URLSAFE[((n >> 12) & 63) as usize] as char);
out.push(URLSAFE[((n >> 6) & 63) as usize] as char);
out.push(URLSAFE[(n & 63) as usize] as char);
i += 3;
}
let rem = buf.len() - i;
if rem == 1 {
let n = (buf[i] as u32) << 16;
out.push(URLSAFE[((n >> 18) & 63) as usize] as char);
out.push(URLSAFE[((n >> 12) & 63) as usize] as char);
} else if rem == 2 {
let n = ((buf[i] as u32) << 16) | ((buf[i + 1] as u32) << 8);
out.push(URLSAFE[((n >> 18) & 63) as usize] as char);
out.push(URLSAFE[((n >> 12) & 63) as usize] as char);
out.push(URLSAFE[((n >> 6) & 63) as usize] as char);
}
Ok(Value::Text(out))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_hex_len() {
let v = token_hex(Some(&Value::Int(8))).unwrap();
match v {
Value::Text(s) => assert_eq!(s.len(), 16),
_ => panic!("expected text"),
}
}
}