Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(provider): split monolithic models module into sub-modules

Steven Enamakel038c5a839e78
diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/catalog.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/catalog.rs
index ac5e1b644f..3ea0b12374 100644
--- a/crates/openhuman-core/src/channels/controllers/ops/connect/catalog.rs
+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/catalog.rs
@@ -5,12 +5,12 @@ use crate::rpc::RpcOutcome;
use super::super::definitions::{all_channel_definitions, find_channel_definition, ChannelDefinition};
/// List all available channel definitions.
-pub(super) async fn list_channels() -> Result<RpcOutcome<Vec<ChannelDefinition>>, String> {
+pub async fn list_channels() -> Result<RpcOutcome<Vec<ChannelDefinition>>, String> {
Ok(RpcOutcome::new(all_channel_definitions(), vec![]))
}
/// Describe a single channel by id.
-pub(super) async fn describe_channel(
+pub async fn describe_channel(
channel_id: &str,
) -> Result<RpcOutcome<ChannelDefinition>, String> {
let def = find_channel_definition(channel_id)
diff --git a/crates/openhuman-core/src/inference/provider/ops/models.rs b/crates/openhuman-core/src/inference/provider/ops/models.rs
index c97aa99424..db741d59f2 100644
--- a/crates/openhuman-core/src/inference/provider/ops/models.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/models.rs
@@ -1,4 +1,17 @@
-use serde::Serialize;
+//! Model listing (`list_configured_models` and friends) for a configured
+//! provider.
+//!
+//! Sub-modules, by responsibility:
+//! - [`types`] — the [`ModelInfo`] catalog-entry type.
+//! - [`catalog_listing`] — the `list_configured_models*` request/response
+//! pipeline.
+//! - [`managed_provider`] — the managed (`openhuman`) entry synthesis and
+//! session-safety helpers `list_configured_models_from_config` needs.
+//! - [`local_runtime`] — synthesized entries for `ollama` / `lmstudio` when
+//! the user has no matching `cloud_providers` row.
+//! - [`openrouter`] — OpenRouter detection and API-key validation.
+//! - [`parsing`] — parsing the `/models` response envelope into
+//! [`ModelInfo`] entries.
use super::super::openai_codex::{
openai_codex_client_version, openai_codex_user_agent, resolve_openai_codex_routing,
@@ -7,706 +20,28 @@ use super::super::openai_codex::{
};
use super::sanitize::sanitize_api_error;
-include!("models_part_01.rs");
-
-#[derive(Debug, Serialize)]
-pub struct ModelInfo {
- pub id: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub owned_by: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub context_window: Option<u64>,
- /// Human-readable name when the listing supplies one (the managed
- /// `?catalog=` listing does; a bare OpenAI-compatible `/models` does not).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub display_name: Option<String>,
- /// Charged price in USD per 1M tokens, when the listing publishes it.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub input_per_1m: Option<f64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub output_per_1m: Option<f64>,
-}
-
-/// Resolve the API key used to probe a provider's `/models` endpoint.
-///
-/// Cloud providers store their key in auth-profiles.json (via `lookup_key_for_slug`),
-/// but the OMLX local-runtime chip persists its Bearer key in
-/// `config.local_ai.api_key`. When the slug-scoped lookup comes back empty for omlx,
-/// fall back to that local-runtime key so the reachability probe still sends
-/// `Authorization: Bearer` (otherwise the OMLX server returns 401).
-fn resolve_local_runtime_key(
- slug: &str,
- looked_up: String,
- config: &crate::config::Config,
-) -> String {
- let looked_up = looked_up.trim().to_string();
- if !looked_up.is_empty() {
- return looked_up;
- }
- if slug == "omlx" {
- return config
- .local_ai
- .api_key
- .clone()
- .unwrap_or_default()
- .trim()
- .to_string();
- }
- looked_up
-}
-
-pub async fn list_configured_models(
- provider_id: &str,
-) -> Result<crate::rpc::RpcOutcome<serde_json::Value>, String> {
- let config = crate::config::Config::load_or_init()
- .await
- .map_err(|e| e.to_string())?;
-
- list_configured_models_from_config(provider_id, &config).await
-}
-
-pub async fn list_configured_models_from_config(
- provider_id: &str,
- config: &crate::config::Config,
-) -> Result<crate::rpc::RpcOutcome<serde_json::Value>, String> {
- let provider_id = provider_id.trim().to_string();
- if provider_id.is_empty() {
- return Err("provider_id must not be empty".to_string());
- }
-
- log::debug!("[providers][list_models] provider_id={}", provider_id);
-
- // Explicit `cloud_providers` entry wins (e.g. a user-pointed remote
- // ollama box at https://ollama.example.com/v1). Falling back to the
- // local-runtime synthesis below only happens when no entry matches.
- let entry = config
- .cloud_providers
- .iter()
- .find(|e| e.id == provider_id || e.slug == provider_id)
- .cloned()
- .or_else(|| synthesize_local_runtime_entry(&provider_id, config))
- .or_else(|| synthesize_managed_entry(&provider_id))
- .ok_or_else(|| format!("no cloud provider with id or slug '{}' found", provider_id))?;
-
- let looked_up = crate::inference::provider::factory::lookup_key_for_slug(&entry.slug, config)
- .unwrap_or_default();
- let api_key = resolve_local_runtime_key(&entry.slug, looked_up, config);
-
- let bearer_is_oauth = entry.slug == "openai"
- && crate::inference::provider::factory::openai_bearer_is_oauth(config);
- let routing =
- resolve_openai_codex_routing(config, &entry.slug, &entry.endpoint, &api_key, bearer_is_oauth)
- .unwrap_or_else(|err| {
- log::warn!(
- "[providers][list_models] openai codex routing unavailable; continuing with configured endpoint: {err}"
- );
- OpenAiCodexRouting::standard(&entry.endpoint)
- });
-
- let mut models_url = format!("{}/models", routing.endpoint);
- let codex_client_version = routing.using_oauth.then(openai_codex_client_version);
- if let Some(client_version) = codex_client_version.as_deref() {
- models_url = append_query_param(&models_url, "client_version", client_version);
- }
-
- log::debug!(
- "[providers][list_models] fetching url={} slug={} codex_oauth={} account_id_header={}",
- models_url,
- entry.slug,
- routing.using_oauth,
- routing.account_id.is_some()
- );
-
- let client =
- crate::config::build_runtime_proxy_client_with_timeouts("providers.list_models", 30, 10);
-
- use crate::config::schema::cloud_providers::AuthStyle;
-
- // Managed backend (`openhuman`) needs a different URL *and* a different
- // credential than every BYOK provider above, so neither `entry.endpoint`
- // nor `lookup_key_for_slug` is usable here:
- //
- // * the seeded entry's endpoint is the *chat* base
- // (`https://api.openhuman.ai/v1`), so `{endpoint}/models` would probe
- // the wrong host entirely — the hosted API is resolved by
- // `effective_backend_api_url`, which also ignores an `api_url`
- // override pointing at a local/third-party inference host.
- // * the session JWT lives in the `app-session` auth profile, not
- // `provider:openhuman`, so `lookup_key_for_slug` returns "" and the
- // request would go out unauthenticated (401).
- //
- // `?catalog=openrouter` is required: without it the backend returns only
- // the curated tier list (chat-v1, reasoning-v1, ...), which is deliberately
- // byte-identical to the legacy payload. The catalog listing is gated
- // server-side by OPENROUTER_PASSTHROUGH_ENABLED and returns an empty set
- // when the passthrough is off, so this degrades to "no models" rather than
- // an error on a backend that has not enabled it.
- let mut managed_token = String::new();
- if entry.auth_style == AuthStyle::OpenhumanJwt {
- // Do NOT propagate a missing session: a self-hosted entry may carry a
- // provider-scoped key instead, and the auth arm below documents that
- // fallback. Only fail when neither credential exists, so the error the
- // caller sees names the real problem.
- //
- // Classify the session directly rather than going through
- // `require_live_session_token`, which flattens "signed out" and "could
- // not read the credential store" into one opaque Err. A lock timeout or
- // filesystem error is a recoverable fault the picker should surface —
- // swallowing it into a successful empty catalog hides it (review, #6206).
- // A store error still propagates; only a genuinely absent/expired
- // session degrades to an empty list.
- use crate::security::credentials::session_support::{
- classify_session_token, load_app_session_profile, publish_local_session_expiry,
- SessionTokenCheck,
- };
- let profile = load_app_session_profile(config)?;
- match classify_session_token(profile.as_ref(), chrono::Utc::now()) {
- SessionTokenCheck::Live(token) => managed_token = token,
- // Signed out is not a provider failure. The managed catalog has
- // nothing to offer until there is a session, and managed stays
- // selectable on its automatic routing — so return an empty list
- // rather than surfacing "could not load models".
- check if api_key.is_empty() => {
- let reason = match check {
- SessionTokenCheck::Expired => {
- // Still announce the expiry: `require_live_session_token`
- // did this for us before, and without it an expired token
- // stays in the store with nothing prompting a re-auth.
- publish_local_session_expiry("list_configured_models");
- "session expired"
- }
- _ => "no session",
- };
- log::info!(
- "[providers][list_models] managed catalog unavailable — {reason}; returning an empty list"
- );
- return Ok(crate::rpc::RpcOutcome::new(
- serde_json::json!({ "models": Vec::<ModelInfo>::new() }),
- vec![format!("{reason}; managed catalog is empty")],
- ));
- }
- check => {
- if matches!(check, SessionTokenCheck::Expired) {
- publish_local_session_expiry("list_configured_models");
- }
- log::debug!(
- "[providers][list_models] no live session; falling back to the provider-scoped key"
- );
- }
- }
- let base = crate::api::config::effective_backend_api_url(&config.api_url);
- models_url = append_query_param(
- &crate::api::config::api_url(&base, "/openai/v1/models"),
- "catalog",
- "openrouter",
- );
- log::debug!(
- "[providers][list_models] managed catalog url={}",
- models_url
- );
- }
-
- if is_openrouter_provider(&entry) {
- validate_openrouter_api_key(&client, &routing.endpoint, &api_key).await?;
- }
-
- // Whether the app session token actually made it onto the wire. It is not
- // the same question as "is `managed_token` non-empty": the credential-safety
- // guard below can decline to attach it, and a 401 on an unauthenticated
- // request must not be read as a stale session (review, #6206).
- let mut managed_session_attached = false;
- let mut request = client.get(&models_url);
- if routing.using_oauth {
- request = request
- .header(reqwest::header::USER_AGENT, openai_codex_user_agent())
- .header(OPENAI_CODEX_ORIGINATOR_HEADER, OPENAI_CODEX_ORIGINATOR);
- }
-
- request = match entry.auth_style {
- AuthStyle::Bearer => {
- if !api_key.is_empty() {
- let mut r = request.header("Authorization", format!("Bearer {}", api_key));
- if let Some(account_id) = routing.account_id.as_deref() {
- r = r.header(OPENAI_CODEX_ACCOUNT_HEADER, account_id);
- }
- r
- } else {
- request
- }
- }
- AuthStyle::Anthropic => {
- let mut r = request.header("anthropic-version", "2023-06-01");
- if !api_key.is_empty() {
- r = r.header("x-api-key", &api_key);
- }
- r
- }
- AuthStyle::OpenhumanJwt => {
- // Prefer the live session JWT resolved above; fall back to a
- // provider-scoped key so a self-hosted entry that stores one still
- // authenticates.
- let token = if !managed_token.is_empty() {
- managed_token.as_str()
- } else {
- api_key.as_str()
- };
- managed_session_attached = managed_session_attaches(&managed_token, &models_url);
- // Never put a bearer credential on the wire in clear text. `https`
- // or a loopback host only — loopback stays allowed so a local
- // backend (BACKEND_URL=http://127.0.0.1:...) still works in dev.
- if !token.is_empty() && url_is_credential_safe(&models_url) {
- // Managed traffic is attributed per embedding product
- // (OpenCompany / Medulla / desktop); the generic provider client
- // does not carry it, so attach it explicitly.
- let (name, value) = crate::api::product::product_identity_header();
- request
- .header("Authorization", format!("Bearer {}", token))
- .header(name, value)
- } else if !token.is_empty() {
- log::warn!(
- "[providers][list_models] refusing to send a bearer token to a non-https, non-loopback URL"
- );
- request
- } else {
- request
- }
- }
- AuthStyle::None => request,
- };
-
- let response = request
- .send()
- .await
- .map_err(|e| format!("[providers][list_models] HTTP request failed: {}", e))?;
-
- let status = response.status();
- if !status.is_success() {
- // A 401 from the MANAGED catalog means the caller is not signed in —
- // the stored session was rejected server-side even though its local
- // `exp` was still valid, so `require_live_session_token` handed us a
- // token the backend no longer honours. That is a signed-out state, not
- // a provider failure, and rendering it as "could not load models" put a
- // red error under managed for a user whose only problem is a stale
- // session. Managed stays selectable on its automatic routing, so return
- // an empty catalog and let the app's normal auth surfaces prompt for
- // re-authentication.
- //
- // Scoped to the managed provider on purpose: for a BYOK provider a 401
- // IS the actionable error (a wrong or revoked API key), and hiding it
- // would strand the user with a silently empty dropdown.
- if managed_401_means_signed_out(status.as_u16(), entry.auth_style, managed_session_attached)
- {
- log::info!(
- "[providers][list_models] managed catalog unavailable — backend rejected the session token (401); returning an empty list"
- );
- return Ok(crate::rpc::RpcOutcome::new(
- serde_json::json!({ "models": Vec::<ModelInfo>::new() }),
- vec!["session not accepted; managed catalog is empty".to_string()],
- ));
- }
- let body = response.text().await.unwrap_or_default();
- let sanitized = sanitize_api_error(&body);
- let truncated = crate::util::truncate_with_ellipsis(&sanitized, 300);
- // TAURI-RUST-8X3: a 404 from the `<base>/models` probe means the
- // configured base URL does not host an OpenAI-compatible `/models`
- // listing (wrong base, a model-only proxy, or a missing `/v1`
- // suffix). Append an actionable hint so the model-dropdown probe
- // surfaces *recovery guidance* inline instead of the bare Go-style
- // `404 page not found`. The `provider returned 404` prefix is kept
- // verbatim so the `is_provider_user_state_message` classifier anchor
- // (which demotes this preventable user-state case out of Sentry)
- // still matches — see `crates/openhuman-core/src/core/observability.rs`.
- if status.as_u16() == 404 {
- return Err(format!(
- "provider returned 404: {} — the configured base URL does not expose a `/models` endpoint; check the provider's base URL (it usually ends in `/v1`)",
- truncated
- ));
- }
- return Err(format!(
- "provider returned {}: {}",
- status.as_u16(),
- truncated
- ));
- }
-
- // TAURI-RUST-12: `response.json()` discards the body when decoding fails,
- // so Sentry just sees `error decoding response body` with no clue what the
- // server actually sent. In practice the offending body is HTML from a
- // captive portal / corporate proxy login page, an upstream load-balancer
- // 502 served as HTML with a `200 OK`, or a JSON parser tripping on a
- // wrong-path endpoint. Read the body as text first, then parse, and
- // surface a sanitized + truncated snippet so the failure is diagnosable
- // from the error string alone.
- let raw_body = response.text().await.map_err(|e| {
- format!(
- "[providers][list_models] failed to read response body: {}",
- e
- )
- })?;
- let body: serde_json::Value = serde_json::from_str(&raw_body).map_err(|e| {
- let sanitized = sanitize_api_error(&raw_body);
- let snippet = crate::util::truncate_with_ellipsis(&sanitized, 300);
- format!(
- "[providers][list_models] failed to parse JSON: {} (body: {})",
- e, snippet
- )
- })?;
-
- // OpenAI-compatible servers occasionally return HTTP 200 with an error
- // payload instead of a 4xx (LM Studio does this for unknown paths like
- // `/v11/models` — body `{"error":"Unexpected endpoint or method..."}`).
- // Treat any top-level `error` field as a failure so the AI-panel probe
- // doesn't silently accept a typo'd endpoint.
- if let Some(err_field) = body.get("error") {
- let msg = err_field
- .as_str()
- .map(|s| s.to_string())
- .or_else(|| {
- err_field
- .get("message")
- .and_then(|m| m.as_str())
- .map(|s| s.to_string())
- })
- .unwrap_or_else(|| err_field.to_string());
- let sanitized = sanitize_api_error(&msg);
- return Err(format!("provider returned error payload: {}", sanitized));
- }
-
- // Parse the OpenAI-compatible `/models` envelope into typed model
- // entries. See `parse_models_response` for the distinct error shapes
- // returned for "missing field" vs "field present but wrong type"
- // (TAURI-RUST-4Y). The ChatGPT Codex backend uses a sibling `models`
- // array keyed by `slug`, so that shape is accepted here too.
- let mut models = parse_models_response(&body)?;
- if routing.using_oauth {
- merge_openai_codex_model_hints(&mut models);
- }
-
- log::info!(
- "[providers][list_models] slug={} fetched {} models",
- entry.slug,
- models.len()
- );
-
- Ok(crate::rpc::RpcOutcome::new(
- serde_json::json!({ "models": models }),
- vec![format!("fetched {} models", models.len())],
- ))
-}
-
-/// Parse the OpenAI-compatible `/models` response envelope, or the ChatGPT
-/// Codex backend's sibling `models` envelope, into typed [`ModelInfo`] entries.
-///
-/// Returns distinct errors for the three failure modes the wild has
-/// produced in `inference_list_models` Sentry events:
-///
-/// 1. **Missing `data`/`models` field** — endpoint isn't `/models`-compatible
-/// (user typo'd the base URL, pointed at a vector-DB host, etc.).
-/// 2. **`data`/`models` field present but wrong type** — provider returned
-/// `{"object":"error","data":{…}}` or similar non-array. The error names
-/// the actual JSON type so triage knows what the provider sent.
-/// 3. **Non-object top-level body** — provider returned a bare array,
-/// string, etc. Caught explicitly so the parser doesn't silently
-/// drop into the missing-data arm with a `<non-object>` keys list.
-///
-/// A **null** `data`/`models` field on a **success envelope** is NOT an
-/// error — Ollama's OpenAI-compatible `/v1/models` null-encodes the catalog
-/// (`{"object":"list","data":null}`) when no models are pulled, so it is
-/// treated as an empty model list (TAURI-RUST-874 / TAURI-RUST-875). The
-/// null-as-empty short-circuit is gated on `object` being absent or `"list"`:
-/// a null `data` on an error envelope (`{"object":"error","data":null}`)
-/// instead falls through to failure mode 2 so the provider error still
-/// surfaces in the UI and Sentry.
-///
-/// Per-entry parsing ignores entries that don't have a usable string id/slug
-/// (lax on purpose — many OpenAI-compatible servers include malformed rows for
-/// capabilities they don't fully implement).
-pub fn parse_models_response(body: &serde_json::Value) -> Result<Vec<ModelInfo>, String> {
- let obj = body.as_object().ok_or_else(|| {
- format!(
- "provider response is not a JSON object — endpoint is not OpenAI-compatible (got {} at top level)",
- json_value_kind(body)
- )
- })?;
-
- let (field_name, data_value) = obj
- .get("data")
- .map(|value| ("data", value))
- .or_else(|| obj.get("models").map(|value| ("models", value)))
- .ok_or_else(|| {
- let keys = obj.keys().cloned().collect::<Vec<_>>().join(", ");
- format!(
- "provider response missing `data` or `models` field — endpoint is not OpenAI-compatible (got keys: {})",
- keys
- )
- })?;
-
- // A null `data`/`models` field is a valid empty catalog ONLY on a success
- // envelope: Ollama's OpenAI-compatible `/v1/models` returns
- // `{"object":"list","data":null}` (object="list", the success marker) when
- // no models are pulled. Treat that as an empty model list so a healthy-but-
- // empty local runtime doesn't manufacture a hard error (TAURI-RUST-874 /
- // TAURI-RUST-875).
- //
- // An error body such as `{"object":"error","data":null}` ALSO null-encodes
- // `data`; swallowing it as an empty catalog would hide provider/endpoint
- // failures from the UI and Sentry. So gate on a success envelope: short-
- // circuit only when `object` is absent or "list". Any other `object` value
- // (e.g. "error") with null `data` falls through to the descriptive error
- // below, which surfaces the `object` value for triage. Non-array kinds
- // (object/string/number/bool) likewise fall through.
- let is_success_envelope = obj
- .get("object")
- .and_then(|value| value.as_str())
- .is_none_or(|object| object.eq_ignore_ascii_case("list"));
-
- if data_value.is_null() && is_success_envelope {
- log::info!(
- "[providers][list_models] `{field_name}` is null on a success envelope — provider returned an empty catalog (no models)"
- );
- return Ok(Vec::new());
- }
-
- let data = data_value.as_array().ok_or_else(|| {
- // Include the sibling `object` field if present — OpenAI-shaped
- // servers set it to `"list"` on success and `"error"` (or omit)
- // on failure, so its value is the fastest triage signal for
- // future Sentry events on the wrong-type arm.
- let object_field = obj
- .get("object")
- .map(|v| v.to_string())
- .unwrap_or_else(|| "<absent>".to_string());
- format!(
- "provider response has `{}` field but it is {}, expected array — endpoint may be returning an error envelope (\"object\" = {})",
- field_name,
- json_value_kind(data_value),
- object_field,
- )
- })?;
-
- Ok(data
- .iter()
- .filter_map(model_info_from_catalog_item)
- .collect())
-}
-
-/// Name the JSON value kind for use in `parse_models_response` error
-/// messages. Mirrors `serde_json::Value::*` variants exactly so test
-/// assertions on the rendered token (`object`/`string`/`null`/…) stay
-/// in lock-step with the matcher.
-fn json_value_kind(v: &serde_json::Value) -> &'static str {
- match v {
- serde_json::Value::Null => "null",
- serde_json::Value::Bool(_) => "bool",
- serde_json::Value::Number(_) => "number",
- serde_json::Value::String(_) => "string",
- serde_json::Value::Array(_) => "array",
- serde_json::Value::Object(_) => "object",
- }
-}
-
-pub fn synthesize_local_runtime_entry(
- slug: &str,
- config: &crate::config::Config,
-) -> Option<crate::config::schema::cloud_providers::CloudProviderCreds> {
- use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};
-
- let endpoint = match slug {
- // Ollama's OpenAI-compatible surface at `<base>/v1/models` returns
- // the same `{"data": [...]}` shape the existing parser handles, so
- // we route through that rather than the native `/api/tags`.
- "ollama" => {
- let base = crate::inference::local::ollama_base_url_from_config(config);
- format!("{}/v1", base.trim_end_matches('/'))
- }
- // `lm_studio_base_url` already ends in `/v1`.
- "lmstudio" => crate::inference::local::lm_studio::lm_studio_base_url(config),
- _ => return None,
- };
-
- Some(CloudProviderCreds {
- id: format!("synthetic_local_{slug}"),
- slug: slug.to_string(),
- label: slug.to_string(),
- endpoint,
- // Local runtimes accept unauthenticated requests on loopback.
- // The probe at `<endpoint>/models` runs without an Authorization
- // header — `lookup_key_for_slug` may still return a key, but
- // `AuthStyle::None` ignores it (see auth-style match below).
- auth_style: AuthStyle::None,
- legacy_type: None,
- default_model: None,
- })
-}
-
-pub fn merge_openai_codex_model_hints(models: &mut Vec<ModelInfo>) {
- let mut seen = models
- .iter()
- .map(|model| model.id.to_ascii_lowercase())
- .collect::<std::collections::HashSet<_>>();
-
- for id in OPENAI_CODEX_MODEL_HINTS {
- if seen.insert(id.to_ascii_lowercase()) {
- models.push(ModelInfo {
- id: (*id).to_string(),
- owned_by: Some("openai-codex".to_string()),
- context_window: None,
- display_name: None,
- input_per_1m: None,
- output_per_1m: None,
- });
- }
- }
-}
-
-pub fn is_openrouter_provider(
- entry: &crate::config::schema::cloud_providers::CloudProviderCreds,
-) -> bool {
- if entry.slug.eq_ignore_ascii_case("openrouter") {
- return true;
- }
-
- reqwest::Url::parse(&entry.endpoint)
- .ok()
- .and_then(|url| url.host_str().map(|host| host.to_ascii_lowercase()))
- .is_some_and(|host| host == "openrouter.ai" || host.ends_with(".openrouter.ai"))
-}
-
-pub fn append_query_param(url: &str, key: &str, value: &str) -> String {
- if let Ok(mut parsed) = reqwest::Url::parse(url) {
- parsed.query_pairs_mut().append_pair(key, value);
- return parsed.to_string();
- }
-
- let separator = if url.contains('?') { '&' } else { '?' };
- format!("{url}{separator}{key}={value}")
-}
-
-#[allow(dead_code)]
-pub fn model_items_from_body(body: &serde_json::Value) -> Option<Vec<serde_json::Value>> {
- body.get("data")
- .and_then(|d| d.as_array())
- .or_else(|| body.get("models").and_then(|d| d.as_array()))
- .cloned()
-}
-
-fn model_info_from_catalog_item(item: &serde_json::Value) -> Option<ModelInfo> {
- if let Some(id) = item.as_str().map(str::trim).filter(|id| !id.is_empty()) {
- return Some(ModelInfo {
- id: id.to_string(),
- owned_by: None,
- context_window: None,
- display_name: None,
- input_per_1m: None,
- output_per_1m: None,
- });
- }
-
- let id = item
- .get("id")
- .or_else(|| item.get("slug"))
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|id| !id.is_empty())?
- .to_string();
- let owned_by = item
- .get("owned_by")
- .or_else(|| item.get("owned_by_organization"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
- let context_window = item
- .get("context_length")
- .or_else(|| item.get("context_window"))
- .or_else(|| item.get("max_context_window"))
- .and_then(|v| v.as_u64());
- let display_name = item
- .get("display_name")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(|s| s.to_string());
- // `pricing` is already the CHARGED price per 1M tokens on the managed
- // catalog listing, so it can be surfaced verbatim — no margin math here.
- let pricing = item.get("pricing");
- let price = |key: &str| -> Option<f64> {
- pricing
- .and_then(|p| p.get(key))
- .and_then(|v| v.as_f64())
- .filter(|n| n.is_finite() && *n >= 0.0)
- };
- Some(ModelInfo {
- id,
- owned_by,
- context_window,
- display_name,
- input_per_1m: price("inputPer1M"),
- output_per_1m: price("outputPer1M"),
- })
-}
-
-async fn validate_openrouter_api_key(
- client: &reqwest::Client,
- base: &str,
- api_key: &str,
-) -> Result<(), String> {
- if api_key.is_empty() {
- return Err("OpenRouter API key is required before enabling the provider".to_string());
- }
-
- let key_url = format!("{}/key", base);
- log::debug!("[providers][list_models] validating OpenRouter API key");
- let response = client
- .get(&key_url)
- .header("Authorization", format!("Bearer {api_key}"))
- .send()
- .await
- .map_err(|e| format!("[providers][list_models] OpenRouter key validation failed: {e}"))?;
-
- let status = response.status();
- let text = response.text().await.unwrap_or_default();
- if !status.is_success() {
- let sanitized = sanitize_api_error(&text);
- let truncated = crate::util::truncate_with_ellipsis(&sanitized, 300);
- log::debug!(
- "[providers][list_models] OpenRouter key validation failed status={} body={}",
- status.as_u16(),
- truncated
- );
- return Err(format!(
- "OpenRouter key validation returned {}: {}",
- status.as_u16(),
- truncated
- ));
- }
-
- if let Ok(body) = serde_json::from_str::<serde_json::Value>(&text) {
- if let Some(err_field) = body.get("error") {
- let msg = err_field
- .as_str()
- .map(|s| s.to_string())
- .or_else(|| {
- err_field
- .get("message")
- .and_then(|m| m.as_str())
- .map(|s| s.to_string())
- })
- .unwrap_or_else(|| err_field.to_string());
- let sanitized = sanitize_api_error(&msg);
- log::debug!(
- "[providers][list_models] OpenRouter key validation returned error payload={}",
- sanitized
- );
- return Err(format!(
- "OpenRouter key validation returned error payload: {}",
- sanitized
- ));
- }
- }
-
- Ok(())
-}
+mod catalog_listing;
+mod local_runtime;
+mod managed_provider;
+mod openrouter;
+mod parsing;
+mod types;
+
+pub use types::ModelInfo;
+
+pub use catalog_listing::{append_query_param, list_configured_models, list_configured_models_from_config};
+pub use local_runtime::synthesize_local_runtime_entry;
+pub use openrouter::is_openrouter_provider;
+pub use parsing::{merge_openai_codex_model_hints, model_items_from_body, parse_models_response};
+
+// Cross-submodule wiring: each submodule reaches these through `use super::*;`
+// (mirrors the pre-split `include!`-shared scope).
+use catalog_listing::resolve_local_runtime_key;
+use managed_provider::{
+ managed_401_means_signed_out, managed_session_attaches, synthesize_managed_entry,
+ url_is_credential_safe,
+};
+use openrouter::validate_openrouter_api_key;
#[cfg(test)]
#[path = "models_tests.rs"]
diff --git a/crates/openhuman-core/src/memory/safety/pii.rs b/crates/openhuman-core/src/memory/safety/pii.rs
new file mode 100644
index 0000000000..5530c7d166
--- /dev/null
+++ b/crates/openhuman-core/src/memory/safety/pii.rs
@@ -0,0 +1,1016 @@
+//! Multilingual national-ID and personal-PII redaction.
+//!
+//! Split out of the original `safety.rs` (see [`super`]'s doc comment for
+//! why this policy lives in OpenHuman rather than the memory engine). This
+//! half owns the PII replacement tokens, the normalization/candidate-scan
+//! pipeline, the per-identifier regexes, and their checksum validators
+//! (Luhn, IBAN mod-97, Verhoeff, Spanish DNI/NIE, ...); the generic
+//! secret-pattern scrubber and [`Sanitized`]/[`SanitizationReport`] types
+//! live in [`super::secrets`].
+
+use std::sync::LazyLock;
+
+use regex::Regex;
+
+use super::secrets::{Sanitized, SanitizationReport};
+
+// ---------- Multilingual personal-PII redaction ----------
+//
+// On-device, regex + checksum only, zero network.
+//
+// Design — security first:
+//
+// 1. Checksum gating where possible. CPF, CNPJ, CUIT, credit-card (Luhn),
+// IBAN (mod-97), Aadhaar (Verhoeff), Spanish DNI/NIE (check letter), and
+// US SSN reserved-range filters all reject look-alikes that aren't real
+// identifiers. The false-positive rate from format alone is too high; the
+// checksums bring it back to acceptable.
+//
+// 2. Bypass-resistant. Inputs are normalized before matching, which:
+// - strips zero-width characters (U+200B/200C/200D/FEFF/2060/180E),
+// - folds fullwidth digits (`0-9` fullwidth to ASCII) and fullwidth
+// `.-/:` to their ASCII counterparts,
+// - folds Arabic-Indic and Eastern Arabic-Indic digits to ASCII.
+// Match offsets are mapped back to the original text so we only redact
+// the bytes that actually carry PII; surrounding text is untouched.
+//
+// 3. Overlap-safe. Patterns are run in priority order; later matches that
+// overlap an earlier redaction are dropped, so a credit-card span can't
+// also be partially matched as a phone number.
+//
+// 4. Out of scope. Contextual PII (`"call me at the usual number"`), compound
+// PII (`name + employer + city`), arbitrary names, and freeform dates-of-
+// birth all require NER/LLM and are NOT addressed here. This module is
+// honest about its scope.
+
+// ---------- Replacement tokens ----------
+
+const PII_RFC: &str = "[REDACTED_PII_RFC]";
+const PII_CPF: &str = "[REDACTED_PII_CPF]";
+const PII_CNPJ: &str = "[REDACTED_PII_CNPJ]";
+const PII_CUIT: &str = "[REDACTED_PII_CUIT]";
+const PII_MYNUM: &str = "[REDACTED_PII_MYNUMBER]";
+const PII_PHONE: &str = "[REDACTED_PII_PHONE]";
+const PII_SSN: &str = "[REDACTED_PII_SSN]";
+const PII_CC: &str = "[REDACTED_PII_CREDIT_CARD]";
+const PII_IBAN: &str = "[REDACTED_PII_IBAN]";
+const PII_AADHAAR: &str = "[REDACTED_PII_AADHAAR]";
+const PII_PAN_IN: &str = "[REDACTED_PII_PAN_IN]";
+const PII_NINO: &str = "[REDACTED_PII_NINO]";
+const PII_DNI: &str = "[REDACTED_PII_DNI]";
+const PII_RRN: &str = "[REDACTED_PII_RRN]";
+
+// ---------- Patterns ----------
+
+// Brazilian CPF, formatted: NNN.NNN.NNN-NN
+static CPF_FMT_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{3}\.\d{3}\.\d{3}-\d{2}\b").expect("cpf fmt"));
+// Brazilian CPF, bare: 11 consecutive digits. Checksum-gated; ~1% raw FP.
+static CPF_BARE_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{11}\b").expect("cpf bare"));
+
+// Brazilian CNPJ, formatted: NN.NNN.NNN/NNNN-NN
+static CNPJ_FMT_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{2}\.\d{3}\.\d{3}/\d{4}-\d{2}\b").expect("cnpj fmt"));
+// Brazilian CNPJ, bare: 14 consecutive digits.
+static CNPJ_BARE_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{14}\b").expect("cnpj bare"));
+
+// Argentine CUIT/CUIL: NN-NNNNNNNN-N (formatted only — bare 11-digit with
+// single check digit has ~9% FP on random IDs, too noisy without context).
+static CUIT_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{2}-\d{8}-\d\b").expect("cuit"));
+
+// Mexican RFC: 3-4 letters (incl. Ñ &) + 6 digits + 3 alphanumeric homoclave.
+static RFC_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)\b[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}\b").expect("rfc"));
+
+// Japan My Number (12 digits) gated by a Japanese or English keyword within
+// ~30 chars. Bare 12-digit runs without keyword are too noisy.
+static MYNUM_RE: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"(?:マイナンバー|個人番号|My\s?Number)[\s:はがを、.\-]{0,12}(\d{12})\b")
+ .expect("my number")
+});
+
+// E.164 phone: + followed by 7-15 digits, no separators.
+static PHONE_E164_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\+\d{7,15}\b").expect("e164"));
+
+// NANP (US/Canada) formatted phone. Area code must start 2-9; first digit of
+// central-office code also 2-9 (real NANP rule).
+static PHONE_NANP_RE: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"\b(?:\+?1[\s.\-]?)?\(?([2-9]\d{2})\)?[\s.\-]?([2-9]\d{2})[\s.\-]?(\d{4})\b")
+ .expect("nanp phone")
+});
+
+// US SSN: NNN-NN-NNNN. Range filter applied below.
+static SSN_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{3}-\d{2}-\d{4}\b").expect("ssn"));
+
+// Credit card: 13-19 digits with optional spaces/dashes every 4. Luhn-gated.
+static CC_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b(?:\d[\s\-]?){13,19}\b").expect("credit card"));
+
+// IBAN: 2 letter country code + 2 check digits + 11-30 alphanumeric.
+// Allow optional spaces every 4 chars (common human format).
+static IBAN_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b[A-Z]{2}\d{2}(?:[\s]?[A-Z0-9]){11,30}\b").expect("iban"));
+
+// India Aadhaar: 4-4-4 digit groups (space or hyphen) OR contiguous 12 digits
+// gated by keyword. Verhoeff-checksum-gated when grouped, keyword-gated when
+// bare (Verhoeff alone has ~10% raw FP rate on random 12-digit runs).
+static AADHAAR_FMT_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{4}[\s\-]\d{4}[\s\-]\d{4}\b").expect("aadhaar formatted"));
+static AADHAAR_KW_RE: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"(?i)(?:aadhaar|aadhar|आधार|uidai|uid)[\s:#\-no.]{0,10}(\d{12})\b")
+ .expect("aadhaar keyword")
+});
+
+// India PAN: 5 letters, 4 digits, 1 letter. Very high signal — no checksum.
+static PAN_IN_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)\b[A-Z]{5}\d{4}[A-Z]\b").expect("pan-in"));
+
+// UK NINO: 2 letters + 6 digits + suffix A/B/C/D.
+static NINO_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)\b[A-Z]{2}\d{6}[A-D]\b").expect("nino"));
+
+// Spain DNI: 8 digits + check letter. NIE: starts X/Y/Z, then 7 digits + letter.
+static DNI_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\b\d{8}[A-Z]\b").expect("dni"));
+static NIE_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)\b[XYZ]\d{7}[A-Z]\b").expect("nie"));
+
+// South Korea RRN: NNNNNN-CXXXXXX where C is gender/century digit (1-4).
+static RRN_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\b\d{6}-[1-4]\d{6}\b").expect("rrn"));
+static EMAIL_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b").expect("email"));
+
+// ---------- Public API ----------
+
+/// Redact format-based multilingual PII from `text`.
+///
+/// Runs a Unicode normalization pre-pass to defeat fullwidth-digit and
+/// zero-width-char bypasses. Match indices from the normalized form are
+/// translated back to original byte offsets so only the PII bytes are
+/// replaced — surrounding text (including any preserved fullwidth glyphs)
+/// is untouched.
+pub fn redact_pii(text: &str) -> Sanitized<String> {
+ let mut report = SanitizationReport::default();
+
+ // Fast path: cheap byte pre-filter on the raw text. Fullwidth / Arabic-Indic
+ // digits and folded punctuation only surface after normalization, so a clean
+ // raw scan still re-checks the normalized view before declaring the text PII-
+ // free (mirrors the old two-phase SCREEN check).
+ let raw_cand = scan_candidates(text);
+ if !raw_cand.any() {
+ let nview = NormalizedView::build(text);
+ let ncand = scan_candidates(&nview.normalized);
+ if !ncand.any() {
+ log::trace!(
+ "[pii] redact_pii: no candidate before or after normalization (len={})",
+ text.len()
+ );
+ return Sanitized {
+ value: text.to_string(),
+ report,
+ };
+ }
+ log::debug!("[pii] redact_pii: candidate surfaced only after normalization");
+ return splice_redactions(
+ text,
+ &nview,
+ collect_redactions(&nview.normalized, &ncand),
+ &mut report,
+ );
+ }
+
+ let nview = NormalizedView::build(text);
+ // Gate on candidates from the NORMALIZED text — the precise regexes run
+ // against it, so normalization-induced classes (folded digits) are included.
+ let ncand = scan_candidates(&nview.normalized);
+ let redactions = collect_redactions(&nview.normalized, &ncand);
+ splice_redactions(text, &nview, redactions, &mut report)
+}
+
+/// True if `value` looks like it carries any PII. Used to *reject*
+/// namespace/key inputs at boundary checks (analogous to
+/// [`has_likely_secret`]).
+///
+/// Uses the **strict** match set — only formatted / keyword-gated patterns.
+/// Bare-numeric patterns whose only signal is a digit run (credit card via
+/// Luhn, bare CPF, bare CNPJ) or a phone-shaped digit run (NANP without
+/// separators, E.164 leading `+`) are excluded here because their false-
+/// positive rate against scanner-built namespace/key identifiers (WhatsApp
+/// JIDs like `[email protected]`, telegram numeric peer IDs,
+/// millisecond timestamps, padded counters) is too high to use as a hard
+/// rejection signal. Content scrubbing via [`redact_pii`] still applies
+/// those patterns — false positives are tolerable there because they only
+/// replace bytes inside a string, not reject the whole write.
+pub fn has_likely_pii(value: &str) -> bool {
+ let nview = NormalizedView::build(value);
+ let cand = scan_candidates(&nview.normalized);
+ if !cand.any() {
+ return false;
+ }
+ !collect_strict_redactions(&nview.normalized, &cand).is_empty()
+}
+
+/// True when `value` contains an ordinary email address. Kept separate from
+/// [`has_likely_pii`] because scanner-built identifiers may legitimately
+/// contain email-like `@` segments.
+pub fn has_likely_email(value: &str) -> bool {
+ // Cheap gate: every email requires an `@`. Skip compiling the regex when
+ // the byte is absent (the common namespace/key case).
+ if !value.as_bytes().contains(&b'@') {
+ return false;
+ }
+ EMAIL_RE.is_match(value)
+}
+
+// ---------- Match collection ----------
+
+#[derive(Debug)]
+struct Hit {
+ start: usize, // byte offset in NORMALIZED text
+ end: usize,
+ token: &'static str,
+}
+
+fn collect_redactions(norm: &str, cand: &Candidates) -> Vec<Hit> {
+ collect_redactions_inner(norm, cand, true)
+}
+
+/// Variant of [`collect_redactions`] that omits bare-numeric patterns
+/// whose only signal is a digit-run shape: credit card via Luhn, bare
+/// CPF, bare CNPJ, NANP phones (separators optional, so any 10-11 digit
+/// run starting `[2-9]`/`1[2-9]` matches), and E.164 phones (literal `+`
+/// the only signal). Used for boundary checks like [`has_likely_pii`]
+/// where rejection on such a hit alone would have too many false
+/// positives on scanner-built identifiers (WhatsApp group JIDs
+/// `<phone>-<unix>@g.us`, timestamps, padded counters).
+fn collect_strict_redactions(norm: &str, cand: &Candidates) -> Vec<Hit> {
+ collect_redactions_inner(norm, cand, false)
+}
+
+/// Run only the precise regexes whose class was flagged by [`scan_candidates`].
+/// Priority order (and therefore overlap-resolution) is byte-identical to the
+/// unconditional version; the `if cand.*` guards only decide whether each class
+/// runs, so a flagged class produces exactly the hits it always did.
+fn collect_redactions_inner(norm: &str, cand: &Candidates, include_bare_numeric: bool) -> Vec<Hit> {
+ let mut hits: Vec<Hit> = Vec::new();
+
+ // Priority order: most specific / highest-confidence first.
+ if cand.cpf_fmt {
+ push_checksum(&mut hits, norm, &CPF_FMT_RE, PII_CPF, |s| {
+ valid_cpf(digits(s).as_slice())
+ });
+ }
+ if cand.cnpj_fmt {
+ push_checksum(&mut hits, norm, &CNPJ_FMT_RE, PII_CNPJ, |s| {
+ valid_cnpj(digits(s).as_slice())
+ });
+ }
+ if cand.cuit {
+ push_checksum(&mut hits, norm, &CUIT_RE, PII_CUIT, |s| {
+ valid_cuit(digits(s).as_slice())
+ });
+ }
+
+ // IBAN before credit card: CC can match an IBAN tail of all digits.
+ if cand.iban {
+ push_checksum(&mut hits, norm, &IBAN_RE, PII_IBAN, valid_iban);
+ }
+
+ if include_bare_numeric {
+ // Credit card before bare CPF/CNPJ to avoid catching a 13-19 digit run as CPF/CNPJ.
+ if cand.cc {
+ push_checksum(&mut hits, norm, &CC_RE, PII_CC, valid_luhn);
+ }
+ if cand.cnpj_bare {
+ push_checksum(&mut hits, norm, &CNPJ_BARE_RE, PII_CNPJ, |s| {
+ valid_cnpj(digits(s).as_slice())
+ });
+ }
+ if cand.cpf_bare {
+ push_checksum(&mut hits, norm, &CPF_BARE_RE, PII_CPF, |s| {
+ valid_cpf(digits(s).as_slice())
+ });
+ }
+ }
+
+ if cand.aadhaar_fmt {
+ push_checksum(&mut hits, norm, &AADHAAR_FMT_RE, PII_AADHAAR, |s| {
+ valid_verhoeff(digits(s).as_slice())
+ });
+ }
+ // Keyword-gated Aadhaar redacts only the captured 12-digit group.
+ if cand.aadhaar_kw {
+ push_captured(&mut hits, norm, &AADHAAR_KW_RE, PII_AADHAAR, |digits_str| {
+ valid_verhoeff(digits(digits_str).as_slice())
+ });
+ }
+
+ if cand.dni {
+ push_checksum(&mut hits, norm, &DNI_RE, PII_DNI, valid_dni_es);
+ }
+ if cand.nie {
+ push_checksum(&mut hits, norm, &NIE_RE, PII_DNI, valid_nie_es);
+ }
+ if cand.nino {
+ push_checksum(&mut hits, norm, &NINO_RE, PII_NINO, valid_nino);
+ }
+ if cand.ssn {
+ push_checksum(&mut hits, norm, &SSN_RE, PII_SSN, valid_ssn);
+ }
+ if cand.rrn {
+ push_simple(&mut hits, norm, &RRN_RE, PII_RRN);
+ }
+ if cand.rfc {
+ push_simple(&mut hits, norm, &RFC_RE, PII_RFC);
+ }
+ if cand.pan_in {
+ push_simple(&mut hits, norm, &PAN_IN_RE, PII_PAN_IN);
+ }
+
+ if include_bare_numeric {
+ // Phones: E.164 first (more specific), then NANP. Both are bare-numeric
+ // shapes — NANP allows optional separators (`\b\d{10,11}\b` matches as
+ // `XXX-XXX-XXXX`), and E.164 keys on a literal `+` with no further gate.
+ // Strict callers (boundary checks like `has_likely_pii`) exclude these
+ // so scanner-built namespace/key values (WhatsApp JIDs
+ // `<phone>-<unix>@g.us`, telegram numeric peer IDs) don't get rejected.
+ if cand.phone_e164 {
+ push_simple(&mut hits, norm, &PHONE_E164_RE, PII_PHONE);
+ }
+ if cand.phone_nanp {
+ push_simple(&mut hits, norm, &PHONE_NANP_RE, PII_PHONE);
+ }
+ }
+
+ // My Number — captured digit group only, keyword remains visible.
+ if cand.mynumber {
+ push_captured(&mut hits, norm, &MYNUM_RE, PII_MYNUM, |_| true);
+ }
+
+ dedupe_overlaps(&mut hits);
+ log::debug!(
+ "[pii] collect_redactions strict={} hits={}",
+ !include_bare_numeric,
+ hits.len()
+ );
+ hits
+}
+
+fn push_simple(hits: &mut Vec<Hit>, norm: &str, re: &Regex, token: &'static str) {
+ for m in re.find_iter(norm) {
+ hits.push(Hit {
+ start: m.start(),
+ end: m.end(),
+ token,
+ });
+ }
+}
+
+
+fn push_checksum(
+ hits: &mut Vec<Hit>,
+ norm: &str,
+ re: &Regex,
+ token: &'static str,
+ ok: impl Fn(&str) -> bool,
+) {
+ for m in re.find_iter(norm) {
+ if ok(m.as_str()) {
+ hits.push(Hit {
+ start: m.start(),
+ end: m.end(),
+ token,
+ });
+ }
+ }
+}
+
+fn push_captured(
+ hits: &mut Vec<Hit>,
+ norm: &str,
+ re: &Regex,
+ token: &'static str,
+ ok: impl Fn(&str) -> bool,
+) {
+ for caps in re.captures_iter(norm) {
+ let Some(group) = caps.get(1) else { continue };
+ if ok(group.as_str()) {
+ hits.push(Hit {
+ start: group.start(),
+ end: group.end(),
+ token,
+ });
+ }
+ }
+}
+
+// Sort by start asc, length desc. Then walk in order, dropping any hit whose
+// range overlaps a kept hit. Result: earlier + longer wins; no double-redact.
+fn dedupe_overlaps(hits: &mut Vec<Hit>) {
+ hits.sort_by(|a, b| {
+ a.start
+ .cmp(&b.start)
+ .then((b.end - b.start).cmp(&(a.end - a.start)))
+ });
+ let mut kept: Vec<Hit> = Vec::with_capacity(hits.len());
+ for h in hits.drain(..) {
+ let overlaps = kept.last().is_some_and(|k| h.start < k.end);
+ if !overlaps {
+ kept.push(h);
+ }
+ }
+ *hits = kept;
+}
+
+// Splice redactions (whose indices reference NORMALIZED text) back into the
+// ORIGINAL text via NormalizedView's byte-offset mapping. This preserves
+// non-PII original bytes verbatim (including fullwidth glyphs the user
+// intentionally typed) while still scrubbing detected PII.
+fn splice_redactions(
+ original: &str,
+ nview: &NormalizedView,
+ hits: Vec<Hit>,
+ report: &mut SanitizationReport,
+) -> Sanitized<String> {
+ if hits.is_empty() {
+ return Sanitized {
+ value: original.to_string(),
+ report: *report,
+ };
+ }
+ let mut out = String::with_capacity(original.len());
+ let mut cursor = 0;
+ for h in &hits {
+ let start_orig = nview.norm_to_orig(h.start);
+ let end_orig = nview.norm_to_orig(h.end);
+ if start_orig < cursor || start_orig > original.len() || end_orig > original.len() {
+ continue;
+ }
+ out.push_str(&original[cursor..start_orig]);
+ out.push_str(h.token);
+ cursor = end_orig;
+ }
+ out.push_str(&original[cursor..]);
+ report.pii_redactions += hits.len();
+ Sanitized {
+ value: out,
+ report: *report,
+ }
+}
+
+// ---------- Unicode normalization for matching ----------
+//
+// A pre-pass that defeats fullwidth-digit and zero-width-char bypasses while
+// keeping a byte map back to the original string, so matches found on the
+// normalized view can be spliced onto the exact original bytes.
+
+struct NormalizedView {
+ normalized: String,
+ // For each byte offset i in `normalized`, `byte_map[i]` is the byte offset
+ // in the original string where the corresponding char *starts*.
+ // The last entry maps the normalized length to the original length, so
+ // `norm_to_orig(normalized.len())` is well-defined.
+ byte_map: Vec<usize>,
+}
+
+impl NormalizedView {
+ fn build(original: &str) -> Self {
+ let mut normalized = String::with_capacity(original.len());
+ let mut byte_map: Vec<usize> = Vec::with_capacity(original.len() + 1);
+ for (idx, ch) in original.char_indices() {
+ if is_zero_width(ch) {
+ continue;
+ }
+ let mapped = fold_char(ch);
+ let start = normalized.len();
+ normalized.push(mapped);
+ // One byte_map entry per byte of the normalized char.
+ let added = normalized.len() - start;
+ for _ in 0..added {
+ byte_map.push(idx);
+ }
+ }
+ byte_map.push(original.len());
+ Self {
+ normalized,
+ byte_map,
+ }
+ }
+
+ fn norm_to_orig(&self, norm_byte: usize) -> usize {
+ if norm_byte >= self.byte_map.len() {
+ return *self.byte_map.last().unwrap_or(&0);
+ }
+ self.byte_map[norm_byte]
+ }
+}
+
+fn is_zero_width(c: char) -> bool {
+ matches!(
+ c,
+ '\u{200B}'
+ | '\u{200C}'
+ | '\u{200D}'
+ | '\u{200E}'
+ | '\u{200F}'
+ | '\u{2060}'
+ | '\u{180E}'
+ | '\u{FEFF}'
+ )
+}
+
+fn fold_char(c: char) -> char {
+ match c {
+ // Fullwidth digits 0-9
+ '\u{FF10}'..='\u{FF19}' => char::from_u32(c as u32 - 0xFF10 + 0x30).unwrap_or(c),
+ // Arabic-Indic digits ٠-٩
+ '\u{0660}'..='\u{0669}' => char::from_u32(c as u32 - 0x0660 + 0x30).unwrap_or(c),
+ // Eastern Arabic-Indic digits ۰-۹
+ '\u{06F0}'..='\u{06F9}' => char::from_u32(c as u32 - 0x06F0 + 0x30).unwrap_or(c),
+ // Common fullwidth punctuation we care about for PII formats
+ '\u{FF0D}' => '-',
+ '\u{FF0E}' => '.',
+ '\u{FF0F}' => '/',
+ '\u{FF1A}' => ':',
+ '\u{2010}'..='\u{2015}' => '-', // various unicode hyphens/dashes
+ '\u{2212}' => '-', // minus sign
+ other => other,
+ }
+}
+
+// ---------- Byte-oriented candidate pre-filter ----------
+//
+// Replaces the always-resident combined `RegexSet` (one shared NFA plus a
+// per-thread lazy-DFA cache in *every* process/thread) with a single cheap pass
+// over the raw bytes. The scan derives per-class candidate flags from a handful
+// of structural signals — digit-run lengths, punctuation presence, uppercase /
+// alpha presence, `+`, and case-insensitive keyword probes (including the
+// non-Latin Aadhaar and My-Number keywords). Each flag then decides whether that
+// class's precise validation regex is worth compiling and running; the precise
+// `Regex`es stay `LazyLock`, so a class that never sees a candidate is never
+// compiled at all. At 100–1000 concurrent agents that turns "combined NFA + N
+// thread-local DFA caches resident forever" into "only the regexes a workload
+// actually needs, compiled on first hit".
+//
+// Correctness: every flag is a NECESSARY CONDITION of the class's *precise*
+// regex, so a flag can only over-fire (harmless — the precise regex then simply
+// fails to match), never under-fire on real PII. Consequently, whenever a
+// precise pattern would have matched without the pre-filter, its flag is set and
+// it still runs — output is unchanged. The union of the flags is a superset of
+// the legacy `SCREEN` set (pinned by `prefilter_is_superset_of_legacy_screen`).
+// The NANP phone class gates on the *screen*-entry necessary condition — an
+// internal `digit sep digit` separator OR a `\d{11,}` run (the old SCREEN reached
+// `PHONE_NANP_RE` through both) — faithfully preserving the documented "a bare
+// 10-digit NANP run is never reached" behavior while still redacting a bare
+// `1`+10-digit country-code number — see
+// `redact_pii_does_not_reach_bare_10_digit_nanp_today`.
+
+/// Per-class candidate flags produced by [`scan_candidates`]. A set flag means
+/// "run this class's precise regex"; an unset flag means the class cannot
+/// possibly match, so its regex is skipped (and never compiled).
+#[derive(Default, Clone, Copy)]
+struct Candidates {
+ cpf_fmt: bool,
+ cnpj_fmt: bool,
+ cuit: bool,
+ iban: bool,
+ cc: bool,
+ cnpj_bare: bool,
+ cpf_bare: bool,
+ aadhaar_fmt: bool,
+ aadhaar_kw: bool,
+ dni: bool,
+ nie: bool,
+ nino: bool,
+ ssn: bool,
+ rrn: bool,
+ rfc: bool,
+ pan_in: bool,
+ phone_e164: bool,
+ phone_nanp: bool,
+ mynumber: bool,
+}
+
+impl Candidates {
+ /// True if any class is a candidate — i.e. the text is worth a precise pass.
+ fn any(&self) -> bool {
+ self.cpf_fmt
+ || self.cnpj_fmt
+ || self.cuit
+ || self.iban
+ || self.cc
+ || self.cnpj_bare
+ || self.cpf_bare
+ || self.aadhaar_fmt
+ || self.aadhaar_kw
+ || self.dni
+ || self.nie
+ || self.nino
+ || self.ssn
+ || self.rrn
+ || self.rfc
+ || self.pan_in
+ || self.phone_e164
+ || self.phone_nanp
+ || self.mynumber
+ }
+}
+
+/// Case-insensitive (ASCII-only case folding) substring test over raw bytes.
+/// Non-ASCII bytes compare exactly, so this also serves as an exact matcher for
+/// the multibyte Devanagari / Japanese keyword needles.
+fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {
+ if needle.is_empty() {
+ return true;
+ }
+ if hay.len() < needle.len() {
+ return false;
+ }
+ hay.windows(needle.len())
+ .any(|w| w.iter().zip(needle).all(|(a, b)| a.eq_ignore_ascii_case(b)))
+}
+
+/// Aadhaar keyword needles — ASCII forms plus Devanagari `आधार`.
+const AADHAAR_KEYWORDS: &[&[u8]] = &[b"aadhaar", b"aadhar", b"uidai", b"uid", "आधार".as_bytes()];
+/// My-Number Japanese keyword needles. The English `My\s?Number` variant is
+/// handled separately (see `scan_candidates`) so any `\s` separator between the
+/// two words is recognised, not just a literal space.
+const MYNUMBER_JP_KEYWORDS: &[&[u8]] = &["マイナンバー".as_bytes(), "個人番号".as_bytes()];
+
+/// Single linear pass over the bytes deriving every per-class candidate flag.
+///
+/// Only ASCII structural bytes carry signal here; multibyte UTF-8 lead /
+/// continuation bytes are all `>= 0x80`, so scanning `as_bytes()` for ASCII
+/// digits/punctuation/letters is boundary-safe. Keyword probes run over the
+/// same byte slice so the non-Latin needles match verbatim.
+fn scan_candidates(text: &str) -> Candidates {
+ let bytes = text.as_bytes();
+
+ let mut total_digits: usize = 0;
+ let mut max_digit_run: usize = 0;
+ let mut cur_run: usize = 0;
+ let mut has_dot = false;
+ let mut has_dash = false;
+ let mut has_slash = false;
+ // Any ASCII whitespace separator (space, tab, newline, CR, form feed,
+ // vertical tab). The precise Aadhaar pattern separates its groups with
+ // `[\s-]`, which matches the whole `\s` class — so gating on space/tab
+ // alone would under-fire on newline-separated Aadhaar (a real PII drop).
+ let mut has_ws = false;
+ let mut has_upper = false;
+ let mut has_alpha = false;
+ let mut has_xyz = false;
+ let mut has_plus = false;
+ // NANP-style "separated group" signal: some `[digit or ')'] [sep] [digit]`
+ // window exists (sep ∈ space/tab/./-). This is the necessary condition of
+ // the old SCREEN NANP entry, which required internal separators — keeping
+ // bare separator-less 10-digit runs out of the phone path.
+ let mut nanp_sep = false;
+
+ for (i, &b) in bytes.iter().enumerate() {
+ if b.is_ascii_digit() {
+ total_digits += 1;
+ cur_run += 1;
+ if cur_run > max_digit_run {
+ max_digit_run = cur_run;
+ }
+ } else {
+ cur_run = 0;
+ match b {
+ b'.' => has_dot = true,
+ b'-' => has_dash = true,
+ b'/' => has_slash = true,
+ b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c => has_ws = true,
+ b'+' => has_plus = true,
+ b'A'..=b'Z' => {
+ has_upper = true;
+ has_alpha = true;
+ if matches!(b, b'X' | b'Y' | b'Z') {
+ has_xyz = true;
+ }
+ }
+ b'a'..=b'z' => {
+ has_alpha = true;
+ if matches!(b, b'x' | b'y' | b'z') {
+ has_xyz = true;
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if matches!(b, b' ' | b'\t' | b'.' | b'-') && i > 0 && i + 1 < bytes.len() {
+ let prev = bytes[i - 1];
+ let next = bytes[i + 1];
+ if (prev.is_ascii_digit() || prev == b')') && next.is_ascii_digit() {
+ nanp_sep = true;
+ }
+ }
+ }
+
+ let has_digit = total_digits > 0;
+ let aadhaar_kw = AADHAAR_KEYWORDS.iter().any(|kw| contains_ci(bytes, kw));
+ // English `My\s?Number` accepts any single `\s` between the words, so a tab-
+ // or newline-separated keyword (`My\tNumber`) must still flag. Requiring both
+ // `my` and `number` substrings is a necessary condition of the precise regex
+ // and covers every whitespace variant; it may over-fire (harmless — the
+ // precise `MYNUM_RE` re-checks the separator and the trailing 12 digits).
+ let mynumber = MYNUMBER_JP_KEYWORDS.iter().any(|kw| contains_ci(bytes, kw))
+ || (contains_ci(bytes, b"my") && contains_ci(bytes, b"number"));
+
+ let cand = Candidates {
+ // Formatted CPF `\d{3}\.\d{3}\.\d{3}-\d{2}` — needs digits, `.`, `-`.
+ cpf_fmt: has_digit && has_dot && has_dash,
+ // Formatted CNPJ `\d{2}\.\d{3}\.\d{3}/\d{4}-\d{2}` — adds `/`.
+ cnpj_fmt: has_digit && has_dot && has_slash && has_dash,
+ // CUIT `\d{2}-\d{8}-\d` — needs digits and `-`.
+ cuit: has_digit && has_dash,
+ // IBAN `[A-Z]{2}\d{2}…` — case-sensitive uppercase letters and digits.
+ iban: has_upper && has_digit,
+ // Credit card `(?:\d[\s\-]?){13,19}` — at least 13 digits total.
+ cc: total_digits >= 13,
+ // Bare CNPJ `\d{14}` — a 14-long digit run.
+ cnpj_bare: max_digit_run >= 14,
+ // Bare CPF `\d{11}` — an 11-long digit run.
+ cpf_bare: max_digit_run >= 11,
+ // Formatted Aadhaar `\d{4}[\s-]\d{4}[\s-]\d{4}` — 12 digits + a `\s`/dash
+ // separator (any ASCII whitespace, matching the precise `[\s-]` class).
+ aadhaar_fmt: total_digits >= 12 && (has_ws || has_dash),
+ // Keyword-gated Aadhaar — keyword suffices (precise regex checks digits).
+ aadhaar_kw,
+ // Spain DNI `\d{8}[A-Z]` — 8-run plus a letter.
+ dni: max_digit_run >= 8 && has_alpha,
+ // Spain NIE `[XYZ]\d{7}[A-Z]` — X/Y/Z, 7-run, letter.
+ nie: has_xyz && max_digit_run >= 7 && has_alpha,
+ // UK NINO `[A-Z]{2}\d{6}[A-D]` — letters and a 6-run.
+ nino: max_digit_run >= 6 && has_alpha,
+ // US SSN `\d{3}-\d{2}-\d{4}` — digits and `-`.
+ ssn: has_digit && has_dash,
+ // Korea RRN `\d{6}-[1-4]\d{6}` — a 6-run and `-`.
+ rrn: max_digit_run >= 6 && has_dash,
+ // Mexico RFC `[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}` — a 6-run (leading class may
+ // be all non-ASCII `Ñ`, so gate on the digit run alone, not on letters).
+ rfc: max_digit_run >= 6,
+ // India PAN `[A-Z]{5}\d{4}[A-Z]` — letters and a 4-run.
+ pan_in: max_digit_run >= 4 && has_alpha,
+ // E.164 `\+\d{7,15}` — a `+` and a 7+ digit run.
+ phone_e164: has_plus && max_digit_run >= 7,
+ // NANP — screen-entry necessary condition. The old SCREEN reached
+ // `PHONE_NANP_RE` via either the separated-group pattern OR the long
+ // `\d{11,}` run (which covers a bare `1`+10-digit country-code number
+ // like `12025551234`). A bare 10-digit run still stays out of the phone
+ // path (no internal separator, run length 10 < 11).
+ phone_nanp: nanp_sep || max_digit_run >= 11,
+ // My Number — keyword suffices (precise regex checks the 12 digits).
+ mynumber,
+ };
+
+ log::trace!(
+ "[pii] scan_candidates bytes={} digits={} max_run={} nanp_sep={} any={}",
+ bytes.len(),
+ total_digits,
+ max_digit_run,
+ nanp_sep,
+ cand.any()
+ );
+
+ cand
+}
+
+// ---------- Checksum and structural validators for PII candidates ----------
+
+fn digits(s: &str) -> Vec<u32> {
+ s.chars()
+ .filter(|c| c.is_ascii_digit())
+ .map(|c| c.to_digit(10).expect("ascii digit"))
+ .collect()
+}
+
+fn valid_cpf(d: &[u32]) -> bool {
+ if d.len() != 11 || d.iter().all(|x| *x == d[0]) {
+ return false;
+ }
+ let s1: u32 = (0..9).map(|i| d[i] * (10 - i as u32)).sum();
+ let dv1 = (s1 * 10) % 11 % 10;
+ if dv1 != d[9] {
+ return false;
+ }
+ let s2: u32 = (0..10).map(|i| d[i] * (11 - i as u32)).sum();
+ let dv2 = (s2 * 10) % 11 % 10;
+ dv2 == d[10]
+}
+
+fn valid_cnpj(d: &[u32]) -> bool {
+ if d.len() != 14 || d.iter().all(|x| *x == d[0]) {
+ return false;
+ }
+ let w1: [u32; 12] = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
+ let s1: u32 = (0..12).map(|i| d[i] * w1[i]).sum();
+ let r1 = s1 % 11;
+ let dv1 = if r1 < 2 { 0 } else { 11 - r1 };
+ if dv1 != d[12] {
+ return false;
+ }
+ let w2: [u32; 13] = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
+ let s2: u32 = (0..13).map(|i| d[i] * w2[i]).sum();
+ let r2 = s2 % 11;
+ let dv2 = if r2 < 2 { 0 } else { 11 - r2 };
+ dv2 == d[13]
+}
+
+fn valid_cuit(d: &[u32]) -> bool {
+ if d.len() != 11 {
+ return false;
+ }
+ let w: [u32; 10] = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
+ let s: u32 = (0..10).map(|i| d[i] * w[i]).sum();
+ let r = s % 11;
+ let dv = match r {
+ 0 => 0,
+ 1 => return false,
+ _ => 11 - r,
+ };
+ dv == d[10]
+}
+
+// Luhn — used for credit-card validation.
+fn valid_luhn(s: &str) -> bool {
+ let d = digits(s);
+ if d.len() < 13 || d.len() > 19 {
+ return false;
+ }
+ let mut sum = 0u32;
+ let mut alt = false;
+ for x in d.iter().rev() {
+ let v = if alt {
+ let doubled = x * 2;
+ if doubled > 9 {
+ doubled - 9
+ } else {
+ doubled
+ }
+ } else {
+ *x
+ };
+ sum += v;
+ alt = !alt;
+ }
+ sum.is_multiple_of(10)
+}
+
+// IBAN mod-97. Steps: strip spaces, move first 4 chars to end, expand letters
+// (A=10..Z=35), divide as a big-integer mod 97, require remainder == 1.
+fn valid_iban(s: &str) -> bool {
+ let cleaned: String = s.chars().filter(|c| !c.is_whitespace()).collect();
+ if cleaned.len() < 15 || cleaned.len() > 34 {
+ return false;
+ }
+ if !cleaned.chars().take(2).all(|c| c.is_ascii_alphabetic()) {
+ return false;
+ }
+ if !cleaned[2..4].chars().all(|c| c.is_ascii_digit()) {
+ return false;
+ }
+ let rotated: String = cleaned[4..].chars().chain(cleaned[..4].chars()).collect();
+ let mut remainder: u64 = 0;
+ for c in rotated.chars() {
+ let chunk = if let Some(d) = c.to_digit(10) {
+ d as u64
+ } else if c.is_ascii_alphabetic() {
+ (c.to_ascii_uppercase() as u64) - ('A' as u64) + 10
+ } else {
+ return false;
+ };
+ // Expand into the running remainder digit-by-digit so we never need
+ // u128. Each letter contributes 2 decimal digits.
+ if chunk >= 10 {
+ remainder = (remainder * 100 + chunk) % 97;
+ } else {
+ remainder = (remainder * 10 + chunk) % 97;
+ }
+ }
+ remainder == 1
+}
+
+// Verhoeff — used for Aadhaar.
+const VERHOEFF_D: [[u8; 10]; 10] = [
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
+ [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
+ [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
+ [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
+ [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
+ [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
+ [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
+ [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
+ [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
+];
+const VERHOEFF_P: [[u8; 10]; 8] = [
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
+ [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
+ [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
+ [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
+ [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
+ [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
+ [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
+];
+
+fn valid_verhoeff(d: &[u32]) -> bool {
+ if d.len() != 12 {
+ return false;
+ }
+ // Aadhaar can't start with 0 or 1.
+ if d[0] < 2 {
+ return false;
+ }
+ let mut c: u8 = 0;
+ for (i, digit) in d.iter().rev().enumerate() {
+ c = VERHOEFF_D[c as usize][VERHOEFF_P[i % 8][*digit as usize] as usize];
+ }
+ c == 0
+}
+
+// US SSN reserved/invalid ranges per SSA.
+fn valid_ssn(s: &str) -> bool {
+ let d = digits(s);
+ if d.len() != 9 {
+ return false;
+ }
+ let area = d[0] * 100 + d[1] * 10 + d[2];
+ let group = d[3] * 10 + d[4];
+ let serial = d[5] * 1000 + d[6] * 100 + d[7] * 10 + d[8];
+ if area == 0 || area == 666 || area >= 900 {
+ return false;
+ }
+ if group == 0 || serial == 0 {
+ return false;
+ }
+ true
+}
+
+// Spain DNI check letter — 8 digits mod 23 indexes into a fixed letter table.
+const DNI_LETTERS: &[u8; 23] = b"TRWAGMYFPDXBNJZSQVHLCKE";
+
+fn valid_dni_es(s: &str) -> bool {
+ let upper = s.to_ascii_uppercase();
+ let bytes = upper.as_bytes();
+ if bytes.len() != 9 {
+ return false;
+ }
+ let num_str = &upper[..8];
+ let letter = bytes[8];
+ let Ok(num) = num_str.parse::<u32>() else {
+ return false;
+ };
+ DNI_LETTERS[(num % 23) as usize] == letter
+}
+
+fn valid_nie_es(s: &str) -> bool {
+ let upper = s.to_ascii_uppercase();
+ let bytes = upper.as_bytes();
+ if bytes.len() != 9 {
+ return false;
+ }
+ let prefix = match bytes[0] {
+ b'X' => 0u32,
+ b'Y' => 1,
+ b'Z' => 2,
+ _ => return false,
+ };
+ let Ok(rest) = std::str::from_utf8(&bytes[1..8]) else {
+ return false;
+ };
+ let Ok(num) = rest.parse::<u32>() else {
+ return false;
+ };
+ let composed = prefix * 10_000_000 + num;
+ DNI_LETTERS[(composed % 23) as usize] == bytes[8]
+}
+
+// UK NINO reserved-prefix blacklist.
+fn valid_nino(s: &str) -> bool {
+ let upper = s.to_ascii_uppercase();
+ let bytes = upper.as_bytes();
+ if bytes.len() != 9 {
+ return false;
+ }
+ // First char cannot be D F I Q U V; second cannot be D F I O Q U V.
+ let bad_first = b"DFIQUV";
+ let bad_second = b"DFIOQUV";
+ if bad_first.contains(&bytes[0]) || bad_second.contains(&bytes[1]) {
+ return false;
+ }
+ // Reserved two-letter prefixes.
+ let reserved = ["BG", "GB", "KN", "NK", "NT", "TN", "ZZ"];
+ let prefix = &upper[..2];
+ if reserved.contains(&prefix) {
+ return false;
+ }
+ true
+}