Skip to content

unaiverse.uai.validate

A block that arrives on the network is attacker-controlled JSON. Before the package draws it, describes it to a model or reads an answer against it, validate_block checks its structure against the contract and builds a normalised copy of it called the spec. Every other module works on specs and never on raw objects: parse_message validates each block it extracts, the builders of compose validate what they are about to emit and the reading side trusts the field definitions it finds in a validated form. The narrative guide is Interactive messages.

The validator never raises on bad input. A malformed object comes back with ok equal to False and a list of error codes. A hostile peer can therefore at most make a block degrade to its alt or to its raw text (see parse_message).

Callers import from unaiverse.uai. The package re-exports validate_block, normalize_label, is_iso_date, is_https_url, interactive_fields and field_label. The type predicates (is_str, is_int, is_num, is_bool, is_obj, non_empty) and the regular expressions (ID_RE, NAME_RE, ISO_DATE_RE, MIME_RE, LANG_RE) are helpers that the other modules of the package import from here. They are documented below for completeness.

Object Role
validate_block Checks one parsed block and returns {"ok", "spec", "errors", "kind"}.
interactive_fields The fields of a form spec without its section rows.
field_label The label of a field or its name when it has none.
normalize_label The normal form of a label used for uniqueness and for tolerant matching.
is_iso_date, is_https_url The two checks on strings that the contract defines.
is_str, is_int, is_num, is_bool, is_obj, non_empty Type predicates with the semantics of JavaScript.
ID_RE, NAME_RE, ISO_DATE_RE, MIME_RE, LANG_RE The patterns of ids, field names, dates, MIME types and language tags.
from unaiverse.uai import validate_block

result = validate_block({"v": 1, "type": "media", "src": "https://a.org/x.PNG",
                         "mime": "Image/PNG", "alt": "a", "extra": 1})
# {'ok': True, 'spec': {'v': 1, 'type': 'media', 'src': 'https://a.org/x.PNG', 'mime': 'image/png', 'alt': 'a'},
#  'errors': [], 'kind': 'content'}

validate_block

validate_block(obj) -> dict
Source code in unaiverse/uai/validate.py
def validate_block(obj) -> dict:
    """Validates one parsed block object.

    Args:
        obj: The result of json.loads on a fence body.

    Returns:
        A dict ``{"ok": bool, "spec": dict | None, "errors": list[str], "kind": "content" | "reply" | None}``.
    """
    errors: list[str] = []
    if not is_obj(obj):
        return {"ok": False, "spec": None, "errors": ["not_an_object"], "kind": None}

    if not is_int(obj.get("v")):
        errors.append("v_missing")
    elif obj["v"] > PROTOCOL_VERSION:
        errors.append("v_unsupported")

    has_type = is_str(obj.get("type"))
    has_kind = is_str(obj.get("kind"))
    if has_type == has_kind:
        errors.append("type_and_kind" if has_type else "type_or_kind_missing")
        return {"ok": False, "spec": None, "errors": errors, "kind": None}

    if has_kind:
        if obj["kind"] != "reply":
            errors.append("kind_unknown")
        if not is_str(obj.get("to")) or ID_RE.fullmatch(obj["to"]) is None:
            errors.append("to_invalid")
        if not is_obj(obj.get("values")):
            errors.append("values_invalid")
        if errors:
            return {"ok": False, "spec": None, "errors": errors, "kind": "reply"}
        spec = {"v": obj["v"], "kind": "reply", "to": obj["to"], "values": dict(obj["values"])}

        # The readable projection of the answer travels inside the block (contract, section 3.6), and it is
        # the human rendering of a reply. It is never fatal: one that is missing, empty, not a string or
        # over the cap is dropped, and the block stands on its own.
        alt = obj.get("alt")
        if isinstance(alt, str) and alt.strip() and len(alt) <= MAX_ALT_CHARS:
            spec["alt"] = alt

        # The words the values were read from may travel inside the block too, verbatim: a list of texts,
        # oldest first. The field is transparent (a receiver that does not ask for it never sees it) and,
        # like the alt, never fatal: whatever is not a list of usable texts is dropped. Its size is
        # bounded by the fence cap, not by a cap of its own: fidelity is its point.
        raw = obj.get("raw")
        if isinstance(raw, list):
            texts = [t for t in raw if non_empty(t)]
            if texts:
                spec["raw"] = texts
        return {"ok": True, "spec": spec, "errors": errors, "kind": "reply"}

    # Content blocks: alt is mandatory before anything else is looked at
    if not non_empty(obj.get("alt")):
        errors.append("alt_missing")
    elif len(obj["alt"]) > MAX_ALT_CHARS:
        errors.append("alt_too_long")

    block_type = obj["type"]
    if block_type.startswith("x-"):
        if errors:
            return {"ok": False, "spec": None, "errors": errors, "kind": "content"}
        return {"ok": True, "spec": {"v": obj["v"], "type": block_type, "alt": obj["alt"]},
                "errors": errors, "kind": "content"}
    if block_type not in BLOCK_TYPES:
        errors.append("type_unknown")
        return {"ok": False, "spec": None, "errors": errors, "kind": "content"}
    if errors:
        return {"ok": False, "spec": None, "errors": errors, "kind": "content"}

    spec = None
    if block_type == "media":
        spec = _validate_media(obj, errors)
    elif block_type == "data":
        spec = _validate_data(obj, errors)
    elif block_type == "form":
        spec = _validate_form(obj, errors)

    if errors:
        return {"ok": False, "spec": None, "errors": errors, "kind": "content"}
    return {"ok": True, "spec": spec, "errors": errors, "kind": "content"}

Validates one block object as returned by json.loads on the body of a uai fence.

Argument Type Default Meaning
obj any required The parsed body. Anything that is not a dict fails with not_an_object.

The return value is always a dict with four keys.

Key Type Meaning
ok bool True when the block is valid.
spec dict or None The normalised copy of the block when ok is True and None when it is False.
errors list[str] The error codes, empty when ok is True.
kind "content", "reply" or None "reply" for a block with kind, "content" for a block with type and None when the object is not a dict or carries both or neither key.

The checks run in a fixed order and most of them stop at the first failure. The envelope comes first. v must be an integer in the JavaScript sense (1 and 1.0 both pass, True does not) and must not exceed PROTOCOL_VERSION. The object must then carry exactly one of type and kind as a string. A reply block (kind) is checked for kind == "reply", to and values. A content block (type) is checked for its alt first, then for its type, then for the keys of that type.

Normalisation. A valid spec is a new dict and never the input object. Because unknown keys are dropped at every level, a chart configuration or a callback inside a data block is never read. The MIME type of a media block is lower-cased. A select field always carries max (default 1). A section row keeps only type and label. An x-* block keeps only v, type and alt. A reply keeps v, kind, to, a shallow copy of values and, when usable, alt and raw.

Reply blocks. to must match ID_RE and values must be a dict. The values themselves are not checked here because the validator does not know the form. check_reply and apply_canonical check them against it. An alt that is missing, blank, not a string or longer than MAX_ALT_CHARS is dropped without an error. The same holds for raw. The validator keeps the non-blank strings of a list and drops the key when none survives.

validate_block({"v": 1, "kind": "reply", "to": "f", "values": {"x": 1}, "alt": "", "raw": ["", "hi", 3]})
# {'ok': True, 'spec': {'v': 1, 'kind': 'reply', 'to': 'f', 'values': {'x': 1}, 'raw': ['hi']},
#  'errors': [], 'kind': 'reply'}

Field types. A field whose type is not one of FIELD_TYPES degrades to "text". The degraded field keeps name, label, required, help and a string default. Its ui and every key specific to a type (maxLength, format, placeholder, min, max, unit, options) are dropped. Any known type keeps a string ui untouched and drops a ui that is not a string.

validate_block({"v": 1, "type": "form", "id": "f", "name": "n", "alt": "a",
                "fields": [{"name": "x", "type": "color", "ui": "wheel", "default": "red", "maxLength": 3}]})
# spec["fields"] == [{'name': 'x', 'type': 'text', 'default': 'red'}]

Error codes. Codes that concern a single field end with : and the name of the field. The list below is complete for the current version.

Code Block Cause
not_an_object any The body is not a JSON object.
v_missing any v is absent or not an integer.
v_unsupported any v is greater than PROTOCOL_VERSION.
type_and_kind any Both type and kind are strings.
type_or_kind_missing any Neither type nor kind is a string.
kind_unknown reply kind is not "reply".
to_invalid reply to is not an id of 1 to 32 characters in [A-Za-z0-9_-].
values_invalid reply values is not an object.
alt_missing content alt is absent, not a string or blank.
alt_too_long content alt exceeds 2000 characters.
type_unknown content type is neither a block type nor an x-* type.
src_invalid, poster_invalid media The URL is not https with a host.
mime_invalid media mime is blank or does not match MIME_RE.
title_invalid media title is not a string or exceeds 120 characters.
chart_invalid data chart is not one of bar, line and pie.
series_invalid data series is not a list of 1 to 10 items.
series_item_invalid data A series is not an object with a string label and a list of at most 500 points.
point_invalid data A point is not a pair [x, y] with x a string or a finite number and y a finite number.
id_invalid form id does not match ID_RE.
name_invalid form name is blank, not a string or longer than 120 characters.
lang_invalid form lang does not match LANG_RE.
aiHint_invalid form aiHint is not a string or exceeds 2000 characters.
progress_invalid form progress is not two integers with 1 <= step <= total.
fields_invalid form fields is not a list of 1 to 40 items.
field_invalid form An item of fields is not an object.
section_invalid form A section row has a blank label or one over 120 characters.
no_interactive_field form Every item is a section row.
too_many_fields form More than 20 interactive fields.
name_duplicate:<name> form Two fields share a name.
field_name_invalid field name does not match NAME_RE. This code carries no name because the name is the problem.
label_invalid:<name>, help_invalid:<name>, placeholder_invalid:<name> field Not a string or longer than 120 (label) or 240 (help, placeholder) characters.
required_invalid:<name> field required is not a boolean.
maxLength_invalid:<name> field maxLength is not an integer of at least 1.
format_invalid:<name> field format of a text field is not email, url or tel.
min_invalid:<name>, max_invalid:<name> field A bound of the wrong type (a number, an integer, an ISO date). For a select it is a max under 1 or a min outside 0..max.
range_invalid:<name> field min is greater than max.
unit_invalid:<name> field unit is blank or longer than 16 characters.
default_invalid:<name> field default is not a valid value of the type.
options_invalid:<name> field options is not a list of 1 to 50 items.
option_invalid:<name> field An option is not an object with a string value and a non-blank label of at most 120 characters.
option_label_comma:<name> field An option label contains a comma. A comma separates the items of a multiple answer.
option_label_duplicate:<name> field Two labels are equal after normalize_label.
option_value_duplicate:<name> field Two options share a value.
option_help_invalid:<name>, option_media_invalid:<name> field The help of an option is not a string of at most 240 characters. The media of an option is not an https URL.
validate_block({"v": 1, "type": "form", "id": "f", "name": "n", "alt": "a",
                "fields": [{"type": "section", "label": "Part 1"},
                           {"name": "age", "type": "integer", "min": 10, "max": 5}]})
# {'ok': False, 'spec': None, 'errors': ['range_invalid:age'], 'kind': 'content'}

validate_block({"type": "media", "kind": "reply"})
# {'ok': False, 'spec': None, 'errors': ['v_missing', 'type_and_kind'], 'kind': None}

The current version has a few gaps that a caller should know about.

  • v is checked only from above. A block with "v": 0 or "v": -3 is valid.
  • The contract allows one form per message. The validator sees one block at a time and cannot enforce it. parse_message returns every valid form of a message.
  • A select may declare a max greater than the number of its options. A multi-select default may repeat a value and may hold more values than max.
  • The label of a series in a data block has no length limit.
  • For date fields the bounds are compared as strings. ISO dates compare correctly in this way.

interactive_fields

interactive_fields(spec) -> list[dict]
Source code in unaiverse/uai/validate.py
def interactive_fields(spec) -> list[dict]:
    """Returns the interactive fields of a validated form spec, skipping the section rows."""
    fields = (spec or {}).get("fields") or []
    return [f for f in fields if f.get("type") != "section"]

Returns the interactive fields of a form spec in their order and skips the section rows. The argument spec is a validated form spec (dict). None, a spec without fields and any non-form spec give []. Every function of the package that walks the fields of a form goes through this one.

interactive_fields({"fields": [{"type": "section", "label": "P"}, {"name": "a", "type": "text"}]})
# [{'name': 'a', 'type': 'text'}]

field_label

field_label(f: dict) -> str
Source code in unaiverse/uai/validate.py
def field_label(f: dict) -> str:
    """Returns the human label of a field, falling back to its name when the author gave none."""
    return f["label"] if "label" in f else f["name"]

Returns the human label of a field (str). The argument f is one validated field. When the author gave no label the function returns the name (field_label({"name": "x"}) returns "x"). The generated instruction, the readable projection and the corrective prompts all name fields through this function.

normalize_label

normalize_label(s) -> str
Source code in unaiverse/uai/validate.py
def normalize_label(s) -> str:
    """Normalises a label for uniqueness and for tolerant matching: trim, collapse whitespace runs, lower case.

    This is deliberately the whole rule: no diacritics folding (the JavaScript mirror has none either, and
    stripping accents would reject as duplicates two option labels that the receiver accepts) and no casefold
    (which would map some characters differently from JavaScript's toLowerCase).
    """
    return re.sub(r"\s+", " ", ("" if s is None else str(s)).strip()).lower()

Returns the normal form of a label. The function strips leading and trailing whitespace, collapses every run of whitespace to one space and lower-cases the result with str.lower. None becomes "" and any other value is first converted with str. The validator uses it to reject two option labels that differ only in case or spacing. The reading side uses it to match keys and options written by a person or a model.

normalize_label("  Nome   COMPLETO ")   # 'nome completo'

The rule deliberately does no accent folding and no casefold. Both would make Python accept or reject labels differently from the JavaScript implementation.

is_iso_date

is_iso_date(s) -> bool
Source code in unaiverse/uai/validate.py
def is_iso_date(s) -> bool:
    """Tells whether a string is a valid ISO calendar date (YYYY-MM-DD, existing day)."""
    if not isinstance(s, str) or ISO_DATE_RE.fullmatch(s) is None:
        return False
    year, month, day = (int(x) for x in s.split("-"))
    if month < 1 or month > 12 or day < 1 or year < 1:
        return False
    return day <= calendar.monthrange(year, month)[1]

Returns True when s is a string of the form YYYY-MM-DD (ASCII digits) that names a day of the calendar. The day is checked against the real length of its month in that year. February 29 is therefore valid only in a leap year. The year must be at least 1. Anything that is not a string returns False.

is_iso_date("2024-02-29")   # True
is_iso_date("2024-02-30")   # False
is_iso_date("0000-01-01")   # False

is_https_url

is_https_url(s) -> bool
Source code in unaiverse/uai/validate.py
def is_https_url(s) -> bool:
    """Accepts https and nothing else, so that a hostile javascript: or data: URL never survives."""
    if not isinstance(s, str):
        return False
    try:
        parts = urllib.parse.urlsplit(s)
    except ValueError:
        return False
    return parts.scheme == "https" and len(parts.netloc) > 0

Returns True when s is a string that parses as a URL with scheme https and a non-empty host. The scheme comparison is exact and lower case. The check exists to keep javascript:, data: and http: URLs out of src, poster and option media.

is_https_url("https://a.org/x.png")   # True
is_https_url("https://")              # False
is_https_url("javascript:alert(1)")   # False

is_str

is_str(v) -> bool
Source code in unaiverse/uai/validate.py
def is_str(v) -> bool:
    return isinstance(v, str)

Returns True when v is a str.

is_int

is_int(v) -> bool
Source code in unaiverse/uai/validate.py
def is_int(v) -> bool:
    """Mirrors JavaScript's Number.isInteger: a float with no fractional part is an integer, a bool is not."""
    if isinstance(v, bool):
        return False
    if isinstance(v, int):
        return True
    return isinstance(v, float) and math.isfinite(v) and v.is_integer()

Returns True when v is an integer in the sense of JavaScript Number.isInteger. Such a value is an int that is not a bool or a finite float with no fractional part. is_int(3.0) is True and is_int(True) is False. The validator uses it for v, maxLength, progress and the bounds of integer fields. A value such as 3.0 therefore passes as an integer and stays a float in the spec.

is_num

is_num(v) -> bool
Source code in unaiverse/uai/validate.py
def is_num(v) -> bool:
    return not isinstance(v, bool) and isinstance(v, (int, float)) and math.isfinite(v)

Returns True when v is a finite int or float that is not a bool. NaN and the infinities return False.

is_bool

is_bool(v) -> bool
Source code in unaiverse/uai/validate.py
def is_bool(v) -> bool:
    return isinstance(v, bool)

Returns True when v is a bool.

is_obj

is_obj(v) -> bool
Source code in unaiverse/uai/validate.py
def is_obj(v) -> bool:
    return isinstance(v, dict)

Returns True when v is a dict.

non_empty

non_empty(v) -> bool
Source code in unaiverse/uai/validate.py
def non_empty(v) -> bool:
    return isinstance(v, str) and len(v.strip()) > 0

Returns True when v is a string that still holds a character after strip(). non_empty(" ") is False.

ID_RE module-attribute

ID_RE = re.compile('[A-Za-z0-9_-]{1,32}')

The compiled pattern of a form id and of the to of a reply: 1 to 32 characters from [A-Za-z0-9_-]. The validator applies it with fullmatch. The character classes are written out because \d in Python also matches non-ASCII digits.

NAME_RE module-attribute

NAME_RE = re.compile('[A-Za-z_][A-Za-z0-9_]{0,63}')

The compiled pattern of a field name: a letter or _ followed by at most 63 letters, digits or _. The contract limit of 64 characters comes from this pattern.

ISO_DATE_RE module-attribute

ISO_DATE_RE = re.compile('[0-9]{4}-[0-9]{2}-[0-9]{2}')

The compiled pattern [0-9]{4}-[0-9]{2}-[0-9]{2} that is_iso_date applies before checking the calendar.

MIME_RE module-attribute

MIME_RE = re.compile('[a-z0-9.+*-]+/[a-z0-9.+*-]+', re.IGNORECASE)

The compiled pattern of a MIME type, type/subtype with letters, digits and . + * - on both sides, matched without regard to case. The validator lower-cases the MIME type it stores.

LANG_RE module-attribute

LANG_RE = re.compile('[a-z]{2,3}(-[A-Za-z0-9]{2,8})*')

The compiled pattern of the lang of a form: two or three lower-case letters followed by any number of subtags of 2 to 8 letters or digits, each introduced by -. "it", "en-GB" and "pt-BR" match. "EN" and "english" do not. The wording then follows the primary subtag (see template_for).