From 95df7b1884457f46e863e4d2895ed5bfd24a7ba4 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 17 Nov 2026 21:59:50 +0000
Subject: [PATCH 01/10] Add a C ABI status ledger and bind OCaml only to
exported symbols
proven.h declares 162 functions; the qualified RefC library defines 9 of
them with matching signatures, exports 2 more under conflicting signatures
(proven_init, proven_is_initialized) and 7 symbols the header omits,
including proven_header_codegen_main leaking through -Dmain. The eager
OCaml binding declared 146 and could not load (undefined proven_deinit).
bindings/c/include/proven-abi.tsv records each symbol as exported,
conflict, owed or undeclared, with an idris-refc or zig-legacy backend.
scripts/check-abi-ledger.sh checks it against the preprocessed header and
nm of the real library, in both directions, and test-header-bridge.sh runs
it with planted controls (1 accept, 6 reject, 1 not-run). The OCaml binding
now binds the 7 ledger-exported symbols it declared; full-api-audit.sh
enforces binding <= ledger-exported <= nm and owed disjoint from nm.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01J4QvDi2XA8N9NEXSvCspMr
---
.github/workflows/ocaml-ci.yml | 4 +-
bindings/c/include/proven-abi.tsv | 194 +++
bindings/ocaml/lib/proven.ml | 1351 +-----------------
bindings/ocaml/lib/proven_ffi.ml | 954 +------------
bindings/ocaml/scripts/full-api-audit.sh | 37 +-
bindings/ocaml/test/test_proven.ml | 235 +--
docs/adr/2026-11-17-c-abi-status-ledger.adoc | 133 ++
scripts/check-abi-ledger.sh | 85 ++
scripts/test-abi-ledger.sh | 62 +
scripts/test-header-bridge.sh | 13 +-
10 files changed, 580 insertions(+), 2488 deletions(-)
create mode 100644 bindings/c/include/proven-abi.tsv
create mode 100644 docs/adr/2026-11-17-c-abi-status-ledger.adoc
create mode 100755 scripts/check-abi-ledger.sh
create mode 100755 scripts/test-abi-ledger.sh
diff --git a/.github/workflows/ocaml-ci.yml b/.github/workflows/ocaml-ci.yml
index 0e35f052..5baaa6f9 100644
--- a/.github/workflows/ocaml-ci.yml
+++ b/.github/workflows/ocaml-ci.yml
@@ -22,6 +22,7 @@ on:
- 'src/Proven/SafeHeader/ByteKernel.idr'
- 'src/Proven/FFI/HeaderKernelMain.idr'
- 'bindings/c/include/proven.h'
+ - 'bindings/c/include/proven-abi.tsv'
- '.github/workflows/ocaml-ci.yml'
pull_request:
branches: [main]
@@ -32,6 +33,7 @@ on:
- 'src/Proven/SafeHeader/ByteKernel.idr'
- 'src/Proven/FFI/HeaderKernelMain.idr'
- 'bindings/c/include/proven.h'
+ - 'bindings/c/include/proven-abi.tsv'
- '.github/workflows/ocaml-ci.yml'
workflow_dispatch:
concurrency:
@@ -59,7 +61,7 @@ jobs:
while IFS= read -r raw; do
p="${raw%[.,;:)]}"
case "$p" in
- bindings/ocaml/*|ffi/zig/*|bindings/c/include|bindings/c/include/proven.h|.github/workflows/ocaml-ci.yml|./scripts/symbol-audit.sh|scripts/build-header-refc.sh|src/Proven/SafeHeader/ByteKernel.idr|src/Proven/FFI/HeaderKernelMain.idr)
+ bindings/ocaml/*|ffi/zig/*|bindings/c/include|bindings/c/include/proven.h|bindings/c/include/proven-abi.tsv|.github/workflows/ocaml-ci.yml|./scripts/symbol-audit.sh|scripts/build-header-refc.sh|src/Proven/SafeHeader/ByteKernel.idr|src/Proven/FFI/HeaderKernelMain.idr)
;;
bindings/*/*)
echo "::error file=.github/workflows/ocaml-ci.yml::detachability violation: $p"
diff --git a/bindings/c/include/proven-abi.tsv b/bindings/c/include/proven-abi.tsv
new file mode 100644
index 00000000..058a04fe
--- /dev/null
+++ b/bindings/c/include/proven-abi.tsv
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: MPL-2.0
+# Copyright (c) 2026 Jonathan D.A. Jewell
+#
+# libproven C ABI status ledger. One row per symbol declared in proven.h or
+# exported by libproven. proven.h is the target ABI; this file says which part
+# of it actually exists. Columns are tab-separated:
+#
+# symbol status backend note
+#
+# status exported in proven.h, exported, signature matches the header
+# conflict exported under the header name with an incompatible signature
+# owed in proven.h, not exported; an outstanding ABI obligation
+# undeclared exported, absent from proven.h
+# backend idris-refc computed by the compiled Idris core through RefC
+# zig-legacy computed in Zig; not an Idris-verified implementation
+# - no implementation
+#
+# Bindings may bind only `exported` rows. Checkers fail if an exported row is
+# missing from the library, an owed row appears in it, or a header symbol or
+# library export has no row. Move a row only together with the code change.
+#
+# Rows describe the qualified profile: build_standalone.zig -Dheader-refc on
+# native Linux x86_64 GNU. Without -Dheader-refc, proven_header_has_crlf is
+# still exported but refuses with status -99 (no Idris backend).
+# Producer check: scripts/check-abi-ledger.sh (run by test-header-bridge.sh).
+proven_angle_deg_to_rad owed - -
+proven_angle_normalize_degrees owed - -
+proven_angle_normalize_radians owed - -
+proven_angle_rad_to_deg owed - -
+proven_bloom_add owed - -
+proven_bloom_contains owed - -
+proven_bloom_create owed - -
+proven_bloom_free owed - -
+proven_buffer_append owed - -
+proven_buffer_create owed - -
+proven_buffer_free owed - -
+proven_buffer_get owed - -
+proven_build_info exported zig-legacy -
+proven_calculator_eval owed - -
+proven_callback_clear_all owed - -
+proven_callback_count owed - -
+proven_callback_fire owed - -
+proven_callback_register owed - -
+proven_callback_unregister owed - -
+proven_checksum_crc32 owed - -
+proven_checksum_verify_crc32 owed - -
+proven_circuit_breaker_allow owed - -
+proven_circuit_breaker_create owed - -
+proven_circuit_breaker_failure owed - -
+proven_circuit_breaker_free owed - -
+proven_circuit_breaker_state owed - -
+proven_circuit_breaker_success owed - -
+proven_color_parse_hex owed - -
+proven_color_rgb_to_hsl owed - -
+proven_color_to_hex owed - -
+proven_content_type_can_sniff_dangerous owed - -
+proven_content_type_free owed - -
+proven_content_type_is_json owed - -
+proven_content_type_is_xml owed - -
+proven_content_type_parse owed - -
+proven_content_type_render owed - -
+proven_cookie_build_delete owed - -
+proven_cookie_build_set_cookie owed - -
+proven_cookie_get_prefix owed - -
+proven_cookie_has_injection owed - -
+proven_cookie_validate_name owed - -
+proven_cookie_validate_value owed - -
+proven_crypto_constant_time_eq owed - -
+proven_crypto_random_bytes owed - -
+proven_currency_format owed - -
+proven_currency_parse owed - -
+proven_datetime_days_in_month owed - -
+proven_datetime_format_iso8601 owed - -
+proven_datetime_is_leap_year owed - -
+proven_datetime_parse owed - -
+proven_deinit owed - -
+proven_digest_parse owed - -
+proven_digest_to_string owed - -
+proven_digest_verify owed - -
+proven_email_is_valid owed - -
+proven_ffi_abi_version exported zig-legacy -
+proven_float_div owed - -
+proven_float_is_finite owed - -
+proven_float_is_nan owed - -
+proven_float_ln owed - -
+proven_float_sqrt owed - -
+proven_free undeclared zig-legacy -
+proven_free_string exported zig-legacy -
+proven_geo_distance owed - -
+proven_geo_in_bounds owed - -
+proven_geo_validate owed - -
+proven_get_string undeclared zig-legacy -
+proven_graph_add_edge owed - -
+proven_graph_create owed - -
+proven_graph_free owed - -
+proven_graph_has_edge owed - -
+proven_header_build_csp owed - -
+proven_header_build_hsts owed - -
+proven_header_codegen_main undeclared idris-refc RefC program main renamed by -Dmain; not an API; should not be exported
+proven_header_has_crlf exported idris-refc -
+proven_header_is_dangerous owed - -
+proven_header_is_valid_name owed - -
+proven_header_render owed - -
+proven_hex_decode owed - -
+proven_hex_encode owed - -
+proven_hex_free owed - -
+proven_http_parse_www_authenticate owed - -
+proven_http_url_decode owed - -
+proven_http_url_encode owed - -
+proven_init conflict zig-legacy header int32_t(void); export ?*Handle(void)
+proven_is_initialized conflict zig-legacy header bool(void); export u32(?*Handle)
+proven_json_get_type owed - -
+proven_json_is_valid owed - -
+proven_last_error undeclared zig-legacy -
+proven_lru_create owed - -
+proven_lru_free owed - -
+proven_lru_get owed - -
+proven_lru_put owed - -
+proven_math_abs_safe owed - -
+proven_math_add_checked owed - -
+proven_math_clamp owed - -
+proven_math_div owed - -
+proven_math_mod owed - -
+proven_math_mul_checked owed - -
+proven_math_pow_checked owed - -
+proven_math_sub_checked owed - -
+proven_ml_clamp owed - -
+proven_ml_leaky_relu owed - -
+proven_ml_relu owed - -
+proven_ml_sigmoid owed - -
+proven_ml_softmax owed - -
+proven_module_count owed - -
+proven_monotonic_create owed - -
+proven_monotonic_free owed - -
+proven_monotonic_next owed - -
+proven_network_ipv4_is_loopback owed - -
+proven_network_ipv4_is_private owed - -
+proven_network_parse_ipv4 owed - -
+proven_password_is_common owed - -
+proven_password_validate owed - -
+proven_path_has_traversal exported zig-legacy -
+proven_path_sanitize_filename owed - -
+proven_phone_format_e164 owed - -
+proven_phone_parse owed - -
+proven_probability_and owed - -
+proven_probability_create owed - -
+proven_probability_not owed - -
+proven_probability_or_exclusive owed - -
+proven_process undeclared zig-legacy -
+proven_process_array undeclared zig-legacy -
+proven_queue_create owed - -
+proven_queue_free owed - -
+proven_queue_pop owed - -
+proven_queue_push owed - -
+proven_queue_size owed - -
+proven_rate_limiter_create owed - -
+proven_rate_limiter_free owed - -
+proven_rate_limiter_try_acquire owed - -
+proven_register_callback undeclared zig-legacy -
+proven_registry_has_registry owed - -
+proven_registry_parse owed - -
+proven_registry_to_string owed - -
+proven_retry_delay owed - -
+proven_retry_should_retry owed - -
+proven_state_machine_allow owed - -
+proven_state_machine_create owed - -
+proven_state_machine_free owed - -
+proven_state_machine_state owed - -
+proven_state_machine_transition owed - -
+proven_string_escape_html owed - -
+proven_string_escape_js owed - -
+proven_string_escape_sql owed - -
+proven_string_is_valid_utf8 owed - -
+proven_tensor_create owed - -
+proven_tensor_free owed - -
+proven_tensor_get owed - -
+proven_tensor_matmul owed - -
+proven_tensor_set owed - -
+proven_unit_convert_length owed - -
+proven_unit_convert_temp owed - -
+proven_url_free owed - -
+proven_url_parse owed - -
+proven_uuid_is_nil owed - -
+proven_uuid_parse owed - -
+proven_uuid_to_string owed - -
+proven_uuid_v4 owed - -
+proven_uuid_version owed - -
+proven_version exported zig-legacy -
+proven_version_compare owed - -
+proven_version_free owed - -
+proven_version_major exported zig-legacy -
+proven_version_minor exported zig-legacy -
+proven_version_parse owed - -
+proven_version_patch exported zig-legacy -
diff --git a/bindings/ocaml/lib/proven.ml b/bindings/ocaml/lib/proven.ml
index 09cad8b3..f2142ff7 100644
--- a/bindings/ocaml/lib/proven.ml
+++ b/bindings/ocaml/lib/proven.ml
@@ -1,15 +1,19 @@
(* SPDX-License-Identifier: MPL-2.0 *)
(* Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) *)
-(** Proven: Formally verified safety primitives for OCaml.
+(** Proven: safety primitives for OCaml, bound to libproven.
- This library is a thin FFI wrapper around [libproven], which provides
- formally verified (Idris 2) safety primitives. All computation is
- performed inside the verified Idris 2 core -- this OCaml package does
- data marshaling only.
+ This library marshals data only. It exposes exactly the libproven
+ functions whose C ABI status ledger row ([proven-abi.tsv] beside
+ [proven.h]) is [exported]. Each wrapper names its backend:
- Every public function returns [option] or [result] instead of raising
- exceptions. *)
+ - [SafeHeader.has_crlf] is computed by the compiled Idris core (RefC).
+ - [SafePath.has_traversal] and [Version] are computed in Zig and are not
+ Idris-verified implementations.
+
+ The other [proven.h] functions are owed ABI obligations, not available
+ functions. Every public function returns a plain value or [option]; none
+ raises. *)
open Ctypes
module F = Proven_ffi
@@ -18,7 +22,8 @@ module F = Proven_ffi
(* Internal helpers *)
(* ========================================================================== *)
-(** Allocate a ctypes char pointer from an OCaml string. *)
+(** Copy an OCaml string into a NUL-terminated buffer the caller owns.
+ Embedded NUL bytes are data: the length passed to C is [String.length]. *)
let cstring_of_string (s : string) : char ptr =
let len = String.length s in
let buf = allocate_n char ~count:(len + 1) in
@@ -28,74 +33,19 @@ let cstring_of_string (s : string) : char ptr =
(buf +@ len) <-@ '\000';
buf
-(** Read a C string (pointer + length) into an OCaml string, then free it
- via [proven_free_string]. *)
-let read_and_free_string (p : char ptr) (len : Unsigned.size_t) : string =
- let n = Unsigned.Size_t.to_int len in
- let s = Bytes.create n in
- for i = 0 to n - 1 do
- Bytes.set s i !@(p +@ i)
- done;
- F.proven_free_string p;
- Bytes.to_string s
-
-(** Check if a status value is ok (== 0). *)
-let status_ok (s : int32) : bool =
- Int32.equal s F.proven_status_ok
-
-(** Unwrap an IntResult into [Some int64] if ok, [None] otherwise. *)
-let unwrap_int_result (r : F.int_result structure) : int64 option =
- if status_ok (getf r F.ir_status) then
- Some (getf r F.ir_value)
- else
- None
-
(** Unwrap a BoolResult into [Some bool] if ok, [None] otherwise. *)
let unwrap_bool_result (r : F.bool_result structure) : bool option =
- if status_ok (getf r F.br_status) then
+ if Int32.equal (getf r F.br_status) F.proven_status_ok then
Some (getf r F.br_value)
else
None
-(** Unwrap a StringResult into [Some string] if ok, [None] otherwise.
- The C string is freed after copying. *)
-let unwrap_string_result (r : F.string_result structure) : string option =
- if status_ok (getf r F.sr_status) then
- let p = getf r F.sr_value in
- let len = getf r F.sr_length in
- if is_null p then None
- else Some (read_and_free_string p len)
- else
- None
-
-(** Unwrap a FloatResult into [Some float] if ok, [None] otherwise. *)
-let unwrap_float_result (r : F.float_result structure) : float option =
- if status_ok (getf r F.fr_status) then
- Some (getf r F.fr_value)
- else
- None
-
-(* ========================================================================== *)
-(* Lifecycle *)
-(* ========================================================================== *)
-
-module Lifecycle = struct
- (** Initialize libproven. Returns [true] if initialization succeeded. *)
- let init () : bool =
- let rc = F.proven_init () in
- Int32.equal rc 0l
-
- (** Deinitialize libproven. *)
- let deinit () : unit =
- F.proven_deinit ()
-
- (** Check whether libproven has been initialized. *)
- let is_initialized () : bool =
- F.proven_is_initialized ()
-end
+let check_span call (s : string) : bool option =
+ let p = cstring_of_string s in
+ unwrap_bool_result (call p (Unsigned.Size_t.of_int (String.length s)))
(* ========================================================================== *)
-(* Version *)
+(* Version (zig-legacy) *)
(* ========================================================================== *)
module Version = struct
@@ -114,1267 +64,34 @@ module Version = struct
(** FFI ABI version. *)
let abi_version () : int =
Unsigned.UInt32.to_int (F.proven_ffi_abi_version ())
-
- (** Number of modules in libproven. *)
- let module_count () : int =
- Unsigned.UInt32.to_int (F.proven_module_count ())
-end
-
-(* ========================================================================== *)
-(* SafeMath *)
-(* ========================================================================== *)
-
-module SafeMath = struct
- (** Safe division. Returns [None] on division by zero. *)
- let div (a : int) (b : int) : int option =
- unwrap_int_result (F.proven_math_div (Int64.of_int a) (Int64.of_int b))
- |> Option.map Int64.to_int
-
- (** Safe modulo. Returns [None] on division by zero. *)
- let modulo (a : int) (b : int) : int option =
- unwrap_int_result (F.proven_math_mod (Int64.of_int a) (Int64.of_int b))
- |> Option.map Int64.to_int
-
- (** Checked addition. Returns [None] on overflow. *)
- let add (a : int) (b : int) : int option =
- unwrap_int_result (F.proven_math_add_checked (Int64.of_int a) (Int64.of_int b))
- |> Option.map Int64.to_int
-
- (** Checked subtraction. Returns [None] on underflow. *)
- let sub (a : int) (b : int) : int option =
- unwrap_int_result (F.proven_math_sub_checked (Int64.of_int a) (Int64.of_int b))
- |> Option.map Int64.to_int
-
- (** Checked multiplication. Returns [None] on overflow. *)
- let mul (a : int) (b : int) : int option =
- unwrap_int_result (F.proven_math_mul_checked (Int64.of_int a) (Int64.of_int b))
- |> Option.map Int64.to_int
-
- (** Safe absolute value. Handles MIN_INT correctly. *)
- let abs (n : int) : int option =
- unwrap_int_result (F.proven_math_abs_safe (Int64.of_int n))
- |> Option.map Int64.to_int
-
- (** Clamp value to range [lo, hi]. *)
- let clamp ~lo ~hi (value : int) : int =
- Int64.to_int (F.proven_math_clamp (Int64.of_int lo) (Int64.of_int hi) (Int64.of_int value))
-
- (** Integer power with overflow checking. *)
- let pow (base : int) (exp : int) : int option =
- unwrap_int_result (F.proven_math_pow_checked (Int64.of_int base) (Unsigned.UInt32.of_int exp))
- |> Option.map Int64.to_int
-
- (** 64-bit variants for when OCaml [int] is too narrow. *)
-
- let div64 (a : int64) (b : int64) : int64 option =
- unwrap_int_result (F.proven_math_div a b)
-
- let add64 (a : int64) (b : int64) : int64 option =
- unwrap_int_result (F.proven_math_add_checked a b)
-
- let sub64 (a : int64) (b : int64) : int64 option =
- unwrap_int_result (F.proven_math_sub_checked a b)
-
- let mul64 (a : int64) (b : int64) : int64 option =
- unwrap_int_result (F.proven_math_mul_checked a b)
end
(* ========================================================================== *)
-(* SafeString *)
-(* ========================================================================== *)
-
-module SafeString = struct
- (** Check whether a byte sequence is valid UTF-8. *)
- let is_valid_utf8 (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_string_is_valid_utf8 p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** Escape a string for SQL (single-quote doubling). *)
- let escape_sql (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_string_escape_sql p (Unsigned.Size_t.of_int (String.length s)))
-
- (** Escape HTML angle brackets, ampersands and quotation marks. *)
- let escape_html (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_string_escape_html p (Unsigned.Size_t.of_int (String.length s)))
-
- (** Escape a string for JavaScript (within quotes). *)
- let escape_js (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_string_escape_js p (Unsigned.Size_t.of_int (String.length s)))
-end
-
-(* ========================================================================== *)
-(* SafePath *)
+(* SafePath (zig-legacy) *)
(* ========================================================================== *)
module SafePath = struct
- (** Check whether a path attempts directory traversal. *)
- let has_traversal (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_path_has_traversal p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> true
-
- (** Sanitize a filename by removing dangerous characters. *)
- let sanitize_filename (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_path_sanitize_filename p (Unsigned.Size_t.of_int (String.length s)))
-end
-
-(* ========================================================================== *)
-(* SafeCrypto *)
-(* ========================================================================== *)
-
-module SafeCrypto = struct
- (** Constant-time byte comparison (timing-safe). *)
- let constant_time_eq (a : string) (b : string) : bool =
- let pa = cstring_of_string a in
- let pb = cstring_of_string b in
- let r = F.proven_crypto_constant_time_eq
- pa (Unsigned.Size_t.of_int (String.length a))
- pb (Unsigned.Size_t.of_int (String.length b)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** Fill a buffer with cryptographically secure random bytes.
- Returns [None] on failure. *)
- let random_bytes (n : int) : string option =
- if n <= 0 then Some ""
- else
- let buf = allocate_n char ~count:n in
- let rc = F.proven_crypto_random_bytes buf (Unsigned.Size_t.of_int n) in
- if Int32.equal rc 0l then begin
- let s = Bytes.create n in
- for i = 0 to n - 1 do
- Bytes.set s i !@(buf +@ i)
- done;
- Some (Bytes.to_string s)
- end else
- None
-end
-
-(* ========================================================================== *)
-(* SafeEmail *)
-(* ========================================================================== *)
-
-module SafeEmail = struct
- (** Check whether an email address is valid (RFC 5321 simplified). *)
- let is_valid (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_email_is_valid p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-end
-
-(* ========================================================================== *)
-(* SafeNetwork *)
-(* ========================================================================== *)
-
-module SafeNetwork = struct
- (** Parse an IPv4 address string. Returns the four octets on success. *)
- let parse_ipv4 (s : string) : (int * int * int * int) option =
- let p = cstring_of_string s in
- let r = F.proven_network_parse_ipv4 p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.ipv4r_status) then
- let addr = getf r F.ipv4r_address in
- let octets = getf addr F.ipv4_octets in
- Some (
- Unsigned.UInt8.to_int (CArray.get octets 0),
- Unsigned.UInt8.to_int (CArray.get octets 1),
- Unsigned.UInt8.to_int (CArray.get octets 2),
- Unsigned.UInt8.to_int (CArray.get octets 3)
- )
- else
- None
+ (** Check whether a path attempts directory traversal. Fails closed: a
+ library error is reported as [true]. Use {!has_traversal_result} to
+ distinguish errors. *)
+ let has_traversal_result (s : string) : bool option =
+ check_span F.proven_path_has_traversal s
- (** Check whether an IPv4 address is in a private range (RFC 1918). *)
- let ipv4_is_private (a : int) (b : int) (c : int) (d : int) : bool =
- let addr = make F.ipv4_address in
- let octets = getf addr F.ipv4_octets in
- CArray.set octets 0 (Unsigned.UInt8.of_int a);
- CArray.set octets 1 (Unsigned.UInt8.of_int b);
- CArray.set octets 2 (Unsigned.UInt8.of_int c);
- CArray.set octets 3 (Unsigned.UInt8.of_int d);
- F.proven_network_ipv4_is_private addr
-
- (** Check whether an IPv4 address is loopback (127.0.0.0/8). *)
- let ipv4_is_loopback (a : int) (b : int) (c : int) (d : int) : bool =
- let addr = make F.ipv4_address in
- let octets = getf addr F.ipv4_octets in
- CArray.set octets 0 (Unsigned.UInt8.of_int a);
- CArray.set octets 1 (Unsigned.UInt8.of_int b);
- CArray.set octets 2 (Unsigned.UInt8.of_int c);
- CArray.set octets 3 (Unsigned.UInt8.of_int d);
- F.proven_network_ipv4_is_loopback addr
+ let has_traversal (s : string) : bool =
+ match has_traversal_result s with Some v -> v | None -> true
end
(* ========================================================================== *)
-(* SafeHeader *)
+(* SafeHeader (idris-refc) *)
(* ========================================================================== *)
module SafeHeader = struct
- (** Check for CRLF injection characters in a header value. *)
- let has_crlf (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_header_has_crlf p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> true
-
- (** Check whether a header name is valid per RFC 7230. *)
- let is_valid_name (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_header_is_valid_name p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** Check whether a header name is in the dangerous-headers list. *)
- let is_dangerous (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_header_is_dangerous p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> true
-
- (** Render a validated header string "Name: Value". *)
- let render ~name ~value : string option =
- let pn = cstring_of_string name in
- let pv = cstring_of_string value in
- unwrap_string_result (F.proven_header_render
- pn (Unsigned.Size_t.of_int (String.length name))
- pv (Unsigned.Size_t.of_int (String.length value)))
-
- (** Build a Content-Security-Policy header value from JSON directives. *)
- let build_csp (directives_json : string) : string option =
- let p = cstring_of_string directives_json in
- unwrap_string_result (F.proven_header_build_csp p (Unsigned.Size_t.of_int (String.length directives_json)))
-
- (** Build an HSTS header value. *)
- let build_hsts ~max_age ~include_subdomains ~preload : string option =
- unwrap_string_result (F.proven_header_build_hsts (Int64.of_int max_age) include_subdomains preload)
-end
-
-(* ========================================================================== *)
-(* SafeCookie *)
-(* ========================================================================== *)
-
-module SafeCookie = struct
- (** Check for cookie injection characters. *)
- let has_injection (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_cookie_has_injection p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> true
-
- (** Validate a cookie name. *)
- let validate_name (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_cookie_validate_name p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** Validate a cookie value. *)
- let validate_value (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_cookie_validate_value p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** Get cookie prefix type: 0=none, 1=__Secure-, 2=__Host-. *)
- let get_prefix (s : string) : int option =
- let p = cstring_of_string s in
- unwrap_int_result (F.proven_cookie_get_prefix p (Unsigned.Size_t.of_int (String.length s)))
- |> Option.map Int64.to_int
-
- (** Build a delete-cookie header value. *)
- let build_delete (name : string) : string option =
- let p = cstring_of_string name in
- unwrap_string_result (F.proven_cookie_build_delete p (Unsigned.Size_t.of_int (String.length name)))
-
- (* Note: build_set_cookie requires CookieAttributes struct marshaling.
- Add if needed by extending Proven_ffi with the struct definition. *)
-end
-
-(* ========================================================================== *)
-(* SafeContentType *)
-(* ========================================================================== *)
-
-module SafeContentType = struct
- (** Check whether a content type could be sniffed to something dangerous. *)
- let can_sniff_dangerous (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_content_type_can_sniff_dangerous p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> true
-
- (** Check whether a content type is JSON. *)
- let is_json ~subtype ~suffix : bool =
- let ps = cstring_of_string subtype in
- let pf = cstring_of_string suffix in
- let r = F.proven_content_type_is_json
- ps (Unsigned.Size_t.of_int (String.length subtype))
- pf (Unsigned.Size_t.of_int (String.length suffix)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** Check whether a content type is XML. *)
- let is_xml ~subtype ~suffix : bool =
- let ps = cstring_of_string subtype in
- let pf = cstring_of_string suffix in
- let r = F.proven_content_type_is_xml
- ps (Unsigned.Size_t.of_int (String.length subtype))
- pf (Unsigned.Size_t.of_int (String.length suffix)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-end
-
-(* ========================================================================== *)
-(* SafeUUID *)
-(* ========================================================================== *)
-
-module SafeUUID = struct
- (** Generate a random UUID v4. Returns the 36-character string. *)
- let v4 () : string option =
- let r = F.proven_uuid_v4 () in
- if status_ok (getf r F.ur_status) then
- let u = getf r F.ur_uuid in
- let sr = F.proven_uuid_to_string u in
- unwrap_string_result sr
- else
- None
-
- (** Parse a UUID from its string representation. Returns the 36-char string
- if valid, [None] otherwise. *)
- let parse (s : string) : string option =
- let p = cstring_of_string s in
- let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.ur_status) then
- let u = getf r F.ur_uuid in
- unwrap_string_result (F.proven_uuid_to_string u)
- else
- None
-
- (** Check whether a UUID is nil (all zeros). *)
- let is_nil (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.ur_status) then
- F.proven_uuid_is_nil (getf r F.ur_uuid)
- else
- false
-
- (** Get the UUID version number (1-8). *)
- let version (s : string) : int option =
- let p = cstring_of_string s in
- let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.ur_status) then
- Some (Unsigned.UInt8.to_int (F.proven_uuid_version (getf r F.ur_uuid)))
- else
- None
-
- (** Check whether a string is a valid UUID. *)
- let is_valid (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in
- status_ok (getf r F.ur_status)
-end
-
-(* ========================================================================== *)
-(* SafeJson *)
-(* ========================================================================== *)
-
-module SafeJson = struct
- (** Check whether a string is valid JSON. *)
- let is_valid (s : string) : bool =
- let p = cstring_of_string s in
- let r = F.proven_json_is_valid p (Unsigned.Size_t.of_int (String.length s)) in
- match unwrap_bool_result r with Some v -> v | None -> false
-
- (** JSON value types. *)
- type json_type =
- | Null
- | Bool
- | Number
- | String
- | Array
- | Object
- | Invalid
-
- (** Get the root-level JSON value type. *)
- let get_type (s : string) : json_type =
- let p = cstring_of_string s in
- let t = F.proven_json_get_type p (Unsigned.Size_t.of_int (String.length s)) in
- match Int32.to_int t with
- | 0 -> Null
- | 1 -> Bool
- | 2 -> Number
- | 3 -> String
- | 4 -> Array
- | 5 -> Object
- | _ -> Invalid
-end
-
-(* ========================================================================== *)
-(* SafeDateTime *)
-(* ========================================================================== *)
-
-module SafeDateTime = struct
- (** Parsed date-time components. *)
- type t = {
- year : int;
- month : int;
- day : int;
- hour : int;
- minute : int;
- second : int;
- nanosecond : int;
- tz_offset_minutes : int;
- }
-
- (** Parse an ISO 8601 date/time string. *)
- let parse (s : string) : t option =
- let p = cstring_of_string s in
- let r = F.proven_datetime_parse p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.dtr_status) then
- let dt = getf r F.dtr_datetime in
- Some {
- year = Int32.to_int (getf dt F.dt_year);
- month = Unsigned.UInt8.to_int (getf dt F.dt_month);
- day = Unsigned.UInt8.to_int (getf dt F.dt_day);
- hour = Unsigned.UInt8.to_int (getf dt F.dt_hour);
- minute = Unsigned.UInt8.to_int (getf dt F.dt_minute);
- second = Unsigned.UInt8.to_int (getf dt F.dt_second);
- nanosecond = Unsigned.UInt32.to_int (getf dt F.dt_nanosecond);
- tz_offset_minutes = getf dt F.dt_tz_offset_minutes;
- }
- else
- None
-
- (** Format a date-time as ISO 8601. *)
- let format_iso8601 (t : t) : string option =
- let dt = make F.datetime in
- setf dt F.dt_year (Int32.of_int t.year);
- setf dt F.dt_month (Unsigned.UInt8.of_int t.month);
- setf dt F.dt_day (Unsigned.UInt8.of_int t.day);
- setf dt F.dt_hour (Unsigned.UInt8.of_int t.hour);
- setf dt F.dt_minute (Unsigned.UInt8.of_int t.minute);
- setf dt F.dt_second (Unsigned.UInt8.of_int t.second);
- setf dt F.dt_nanosecond (Unsigned.UInt32.of_int t.nanosecond);
- setf dt F.dt_tz_offset_minutes t.tz_offset_minutes;
- unwrap_string_result (F.proven_datetime_format_iso8601 dt)
-
- (** Check whether a year is a leap year. *)
- let is_leap_year (year : int) : bool =
- F.proven_datetime_is_leap_year (Int32.of_int year)
-
- (** Get the number of days in a month. *)
- let days_in_month ~year ~month : int =
- Unsigned.UInt8.to_int (F.proven_datetime_days_in_month (Int32.of_int year) (Unsigned.UInt8.of_int month))
-end
-
-(* ========================================================================== *)
-(* SafeFloat *)
-(* ========================================================================== *)
-
-module SafeFloat = struct
- (** Safe floating-point division. *)
- let div (a : float) (b : float) : float option =
- unwrap_float_result (F.proven_float_div a b)
-
- (** Check whether a float is finite (not NaN or Inf). *)
- let is_finite (x : float) : bool =
- F.proven_float_is_finite x
-
- (** Check whether a float is NaN. *)
- let is_nan (x : float) : bool =
- F.proven_float_is_nan x
-
- (** Safe square root (returns [None] for negative input). *)
- let sqrt (x : float) : float option =
- unwrap_float_result (F.proven_float_sqrt x)
-
- (** Safe natural logarithm (returns [None] for non-positive input). *)
- let ln (x : float) : float option =
- unwrap_float_result (F.proven_float_ln x)
-end
-
-(* ========================================================================== *)
-(* SafePassword *)
-(* ========================================================================== *)
-
-module SafePassword = struct
- (** Password strength levels. *)
- type strength =
- | Very_weak
- | Weak
- | Fair
- | Strong
- | Very_strong
-
- (** Password validation result. *)
- type validation = {
- strength : strength;
- has_lowercase : bool;
- has_uppercase : bool;
- has_digit : bool;
- has_special : bool;
- length : int;
- }
-
- (** Validate password strength. *)
- let validate (s : string) : validation =
- let p = cstring_of_string s in
- let r = F.proven_password_validate p (Unsigned.Size_t.of_int (String.length s)) in
- let str = match Int32.to_int (getf r F.pw_strength) with
- | 0 -> Very_weak
- | 1 -> Weak
- | 2 -> Fair
- | 3 -> Strong
- | 4 -> Very_strong
- | _ -> Very_weak
- in
- {
- strength = str;
- has_lowercase = getf r F.pw_has_lowercase;
- has_uppercase = getf r F.pw_has_uppercase;
- has_digit = getf r F.pw_has_digit;
- has_special = getf r F.pw_has_special;
- length = Unsigned.Size_t.to_int (getf r F.pw_length);
- }
-
- (** Check whether a password is in the common-passwords list. *)
- let is_common (s : string) : bool =
- let p = cstring_of_string s in
- F.proven_password_is_common p (Unsigned.Size_t.of_int (String.length s))
-end
-
-(* ========================================================================== *)
-(* SafeVersion (semver) *)
-(* ========================================================================== *)
-
-module SafeVersion = struct
- (** Parse a semantic version string. Returns (major, minor, patch) on
- success, or [None] on parse failure. *)
- let parse (s : string) : (int * int * int) option =
- let p = cstring_of_string s in
- let r = F.proven_version_parse_semver p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.vr_status) then begin
- let v = getf r F.vr_version in
- let major = Unsigned.UInt32.to_int (getf v F.sv_major) in
- let minor = Unsigned.UInt32.to_int (getf v F.sv_minor) in
- let patch = Unsigned.UInt32.to_int (getf v F.sv_patch) in
- (* Free the version result (may contain prerelease string) *)
- let vp = allocate F.semantic_version v in
- F.proven_version_free vp;
- Some (major, minor, patch)
- end else
- None
-
- (** Compare two version strings. Returns [Some n] where [n < 0] means
- [a < b], [n = 0] means equal, [n > 0] means [a > b].
- Returns [None] if either string fails to parse. *)
- let compare (a_str : string) (b_str : string) : int option =
- let pa = cstring_of_string a_str in
- let ra = F.proven_version_parse_semver pa (Unsigned.Size_t.of_int (String.length a_str)) in
- if not (status_ok (getf ra F.vr_status)) then None
- else begin
- let pb = cstring_of_string b_str in
- let rb = F.proven_version_parse_semver pb (Unsigned.Size_t.of_int (String.length b_str)) in
- if not (status_ok (getf rb F.vr_status)) then begin
- let vpa = allocate F.semantic_version (getf ra F.vr_version) in
- F.proven_version_free vpa;
- None
- end else begin
- let va = getf ra F.vr_version in
- let vb = getf rb F.vr_version in
- let result = Int32.to_int (F.proven_version_compare va vb) in
- let vpa = allocate F.semantic_version va in
- let vpb = allocate F.semantic_version vb in
- F.proven_version_free vpa;
- F.proven_version_free vpb;
- Some result
- end
- end
-end
-
-(* ========================================================================== *)
-(* SafeGeo *)
-(* ========================================================================== *)
-
-module SafeGeo = struct
- (** Validate and normalize a geographic coordinate.
- Returns [(latitude, longitude)] on success. *)
- let validate ~lat ~lon : (float * float) option =
- let r = F.proven_geo_validate lat lon in
- if status_ok (getf r F.geor_status) then
- let coord = getf r F.geor_coordinate in
- Some (getf coord F.geo_latitude, getf coord F.geo_longitude)
- else
- None
-
- (** Calculate distance between two points in meters (Haversine). *)
- let distance ~lat1 ~lon1 ~lat2 ~lon2 : float option =
- let a = make F.geo_coordinate in
- setf a F.geo_latitude lat1;
- setf a F.geo_longitude lon1;
- let b = make F.geo_coordinate in
- setf b F.geo_latitude lat2;
- setf b F.geo_longitude lon2;
- unwrap_float_result (F.proven_geo_distance a b)
-
- (** Check whether a coordinate is within a bounding box. *)
- let in_bounds ~lat ~lon ~min_lat ~max_lat ~min_lon ~max_lon : bool =
- let coord = make F.geo_coordinate in
- setf coord F.geo_latitude lat;
- setf coord F.geo_longitude lon;
- F.proven_geo_in_bounds coord min_lat max_lat min_lon max_lon
-end
-
-(* ========================================================================== *)
-(* SafeChecksum *)
-(* ========================================================================== *)
-
-module SafeChecksum = struct
- (** Calculate CRC32 of a byte string. *)
- let crc32 (s : string) : int option =
- let p = cstring_of_string s in
- unwrap_int_result (F.proven_checksum_crc32 p (Unsigned.Size_t.of_int (String.length s)))
- |> Option.map Int64.to_int
-
- (** Verify that CRC32 of data matches an expected value. *)
- let verify_crc32 (s : string) (expected : int) : bool =
- let p = cstring_of_string s in
- let r = F.proven_checksum_verify_crc32 p
- (Unsigned.Size_t.of_int (String.length s))
- (Unsigned.UInt32.of_int expected) in
- match unwrap_bool_result r with Some v -> v | None -> false
-end
-
-(* ========================================================================== *)
-(* SafeProbability *)
-(* ========================================================================== *)
-
-module SafeProbability = struct
- (** Create a probability value, clamped to [0, 1]. *)
- let create (v : float) : float =
- F.proven_probability_create v
-
- (** Probability of independent events both occurring (a * b). *)
- let both (a : float) (b : float) : float =
- F.proven_probability_and a b
-
- (** Probability of mutually exclusive events (a + b). *)
- let either_exclusive (a : float) (b : float) : float =
- F.proven_probability_or_exclusive a b
-
- (** Complement probability (1 - p). *)
- let complement (p : float) : float =
- F.proven_probability_not p
-end
-
-(* ========================================================================== *)
-(* SafeCalculator *)
-(* ========================================================================== *)
-
-module SafeCalculator = struct
- (** Evaluate a mathematical expression string. *)
- let eval (expr : string) : float option =
- let p = cstring_of_string expr in
- unwrap_float_result (F.proven_calculator_eval p (Unsigned.Size_t.of_int (String.length expr)))
-end
-
-(* ========================================================================== *)
-(* SafeHex *)
-(* ========================================================================== *)
+ (** Check every byte of a header value for CR or LF. Fails closed: a
+ library error (including an unavailable Idris backend) is reported as
+ [true]. Use {!has_crlf_result} to distinguish errors. *)
+ let has_crlf_result (s : string) : bool option =
+ check_span F.proven_header_has_crlf s
-module SafeHex = struct
- (** Hex-encode bytes. [uppercase] selects A-F vs a-f. *)
- let encode ?(uppercase = false) (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_hex_encode p (Unsigned.Size_t.of_int (String.length s)) uppercase)
-
- (** Hex-decode a string to bytes. *)
- let decode (hex : string) : string option =
- let p = cstring_of_string hex in
- let r = F.proven_hex_decode p (Unsigned.Size_t.of_int (String.length hex)) in
- if status_ok (getf r F.hdr_status) then begin
- let data = getf r F.hdr_data in
- let len = Unsigned.Size_t.to_int (getf r F.hdr_length) in
- if is_null data then None
- else begin
- let s = Bytes.create len in
- for i = 0 to len - 1 do
- Bytes.set s i (Char.chr (Unsigned.UInt8.to_int !@(data +@ i)))
- done;
- let rp = allocate F.hex_decode_result r in
- F.proven_hex_free rp;
- Some (Bytes.to_string s)
- end
- end else
- None
-end
-
-(* ========================================================================== *)
-(* SafeCurrency *)
-(* ========================================================================== *)
-
-module SafeCurrency = struct
- (** Parsed currency amount. *)
- type t = {
- amount_minor : int64;
- currency_code : string;
- decimal_places : int;
- }
-
- (** Parse a currency string (e.g., "USD 123.45"). *)
- let parse (s : string) : t option =
- let p = cstring_of_string s in
- let r = F.proven_currency_parse p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.cur_status) then begin
- let code_arr = getf r F.cur_currency_code in
- let code = Printf.sprintf "%c%c%c"
- (Char.chr (Unsigned.UInt8.to_int (CArray.get code_arr 0)))
- (Char.chr (Unsigned.UInt8.to_int (CArray.get code_arr 1)))
- (Char.chr (Unsigned.UInt8.to_int (CArray.get code_arr 2))) in
- Some {
- amount_minor = getf r F.cur_amount_minor;
- currency_code = code;
- decimal_places = Unsigned.UInt8.to_int (getf r F.cur_decimal_places);
- }
- end else
- None
-
- (** Format a currency amount to string. *)
- let format ~amount_minor ~currency_code ~decimal_places : string option =
- if String.length currency_code <> 3 then None
- else begin
- let code = CArray.make uint8_t 3 in
- CArray.set code 0 (Unsigned.UInt8.of_int (Char.code currency_code.[0]));
- CArray.set code 1 (Unsigned.UInt8.of_int (Char.code currency_code.[1]));
- CArray.set code 2 (Unsigned.UInt8.of_int (Char.code currency_code.[2]));
- unwrap_string_result (F.proven_currency_format amount_minor code (Unsigned.UInt8.of_int decimal_places))
- end
-end
-
-(* ========================================================================== *)
-(* SafePhone *)
-(* ========================================================================== *)
-
-module SafePhone = struct
- (** Parsed phone number. *)
- type t = {
- country_code : int;
- national_number : int64;
- is_valid : bool;
- }
-
- (** Parse a phone number to E.164 components. *)
- let parse (s : string) : t option =
- let p = cstring_of_string s in
- let r = F.proven_phone_parse p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.phr_status) then
- Some {
- country_code = Unsigned.UInt16.to_int (getf r F.phr_country_code);
- national_number = Unsigned.UInt64.to_int64 (getf r F.phr_national_number);
- is_valid = getf r F.phr_is_valid;
- }
- else
- None
-
- (** Format a phone number as E.164 string. *)
- let format_e164 ~country_code ~national_number : string option =
- unwrap_string_result (F.proven_phone_format_e164
- (Unsigned.UInt16.of_int country_code)
- (Unsigned.UInt64.of_int64 national_number))
-end
-
-(* ========================================================================== *)
-(* SafeColor *)
-(* ========================================================================== *)
-
-module SafeColor = struct
- (** RGB color. *)
- type rgb = { r : int; g : int; b : int }
-
- (** HSL color. *)
- type hsl = { h : float; s : float; l : float }
-
- (** Parse a hex color string (#RRGGBB or #RGB). *)
- let parse_hex (s : string) : rgb option =
- let p = cstring_of_string s in
- let r = F.proven_color_parse_hex p (Unsigned.Size_t.of_int (String.length s)) in
- if status_ok (getf r F.cpr_status) then begin
- let c = getf r F.cpr_color in
- Some {
- r = Unsigned.UInt8.to_int (getf c F.rgb_r);
- g = Unsigned.UInt8.to_int (getf c F.rgb_g);
- b = Unsigned.UInt8.to_int (getf c F.rgb_b);
- }
- end else
- None
-
- (** Convert RGB to HSL. *)
- let rgb_to_hsl (color : rgb) : hsl =
- let c = make F.rgb_color in
- setf c F.rgb_r (Unsigned.UInt8.of_int color.r);
- setf c F.rgb_g (Unsigned.UInt8.of_int color.g);
- setf c F.rgb_b (Unsigned.UInt8.of_int color.b);
- let h = F.proven_color_rgb_to_hsl c in
- { h = getf h F.hsl_h; s = getf h F.hsl_s; l = getf h F.hsl_l }
-
- (** Format RGB as hex string. *)
- let to_hex (color : rgb) : string option =
- let c = make F.rgb_color in
- setf c F.rgb_r (Unsigned.UInt8.of_int color.r);
- setf c F.rgb_g (Unsigned.UInt8.of_int color.g);
- setf c F.rgb_b (Unsigned.UInt8.of_int color.b);
- unwrap_string_result (F.proven_color_to_hex c)
-end
-
-(* ========================================================================== *)
-(* SafeAngle *)
-(* ========================================================================== *)
-
-module SafeAngle = struct
- (** Convert degrees to radians. *)
- let deg_to_rad (degrees : float) : float =
- F.proven_angle_deg_to_rad degrees
-
- (** Convert radians to degrees. *)
- let rad_to_deg (radians : float) : float =
- F.proven_angle_rad_to_deg radians
-
- (** Normalize angle to [0, 360) degrees. *)
- let normalize_degrees (degrees : float) : float =
- F.proven_angle_normalize_degrees degrees
-
- (** Normalize angle to [0, 2*pi) radians. *)
- let normalize_radians (radians : float) : float =
- F.proven_angle_normalize_radians radians
-end
-
-(* ========================================================================== *)
-(* SafeUnit *)
-(* ========================================================================== *)
-
-module SafeUnit = struct
- (** Length unit identifiers (matching libproven LengthUnit enum). *)
- type length_unit =
- | Meters | Kilometers | Centimeters | Millimeters
- | Feet | Inches | Miles | Yards
-
- let length_unit_to_int = function
- | Meters -> 0 | Kilometers -> 1 | Centimeters -> 2 | Millimeters -> 3
- | Feet -> 4 | Inches -> 5 | Miles -> 6 | Yards -> 7
-
- (** Temperature unit identifiers (matching libproven TempUnit enum). *)
- type temp_unit = Celsius | Fahrenheit | Kelvin
-
- let temp_unit_to_int = function
- | Celsius -> 0 | Fahrenheit -> 1 | Kelvin -> 2
-
- (** Convert a length value between units. *)
- let convert_length ~from ~to_ (value : float) : float option =
- unwrap_float_result (F.proven_unit_convert_length value
- (Int32.of_int (length_unit_to_int from))
- (Int32.of_int (length_unit_to_int to_)))
-
- (** Convert a temperature value between units. *)
- let convert_temp ~from ~to_ (value : float) : float option =
- unwrap_float_result (F.proven_unit_convert_temp value
- (Int32.of_int (temp_unit_to_int from))
- (Int32.of_int (temp_unit_to_int to_)))
-end
-
-(* ========================================================================== *)
-(* SafeHttp *)
-(* ========================================================================== *)
-
-module SafeHttp = struct
- (** URL-encode a string (RFC 3986 percent encoding). *)
- let url_encode (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_http_url_encode p (Unsigned.Size_t.of_int (String.length s)))
-
- (** URL-decode a percent-encoded string. *)
- let url_decode (s : string) : string option =
- let p = cstring_of_string s in
- unwrap_string_result (F.proven_http_url_decode p (Unsigned.Size_t.of_int (String.length s)))
-end
-
-(* ========================================================================== *)
-(* SafeBuffer *)
-(* ========================================================================== *)
-
-module SafeBuffer = struct
- (** Opaque buffer handle. *)
- type t = F.bounded_buffer structure ptr
-
- (** Create a bounded buffer with the given capacity. *)
- let create (capacity : int) : t option =
- let r = F.proven_buffer_create (Unsigned.Size_t.of_int capacity) in
- if status_ok (getf r F.bufr_status) then
- let buf = getf r F.bufr_buffer in
- if is_null buf then None
- else Some buf
- else
- None
-
- (** Append data to the buffer. Returns [true] on success. *)
- let append (buf : t) (data : string) : bool =
- let p = cstring_of_string data in
- let rc = F.proven_buffer_append buf p (Unsigned.Size_t.of_int (String.length data)) in
- Int32.equal rc 0l
-
- (** Free the buffer. *)
- let free (buf : t) : unit =
- F.proven_buffer_free buf
-end
-
-(* ========================================================================== *)
-(* SafeRateLimiter *)
-(* ========================================================================== *)
-
-module SafeRateLimiter = struct
- (** Opaque rate limiter handle. *)
- type t = F.rate_limiter structure ptr
-
- (** Create a token-bucket rate limiter. *)
- let create ~capacity ~refill_rate : t option =
- F.proven_rate_limiter_create capacity refill_rate
-
- (** Try to acquire [tokens] from the limiter. Returns [true] if allowed. *)
- let try_acquire (rl : t) (tokens : float) : bool =
- F.proven_rate_limiter_try_acquire rl tokens
-
- (** Free the rate limiter. *)
- let free (rl : t) : unit =
- F.proven_rate_limiter_free rl
-end
-
-(* ========================================================================== *)
-(* SafeCircuitBreaker *)
-(* ========================================================================== *)
-
-module SafeCircuitBreaker = struct
- (** Circuit breaker states. *)
- type state = Closed | Open | Half_open
-
- (** Opaque circuit breaker handle. *)
- type t = F.circuit_breaker structure ptr
-
- (** Create a circuit breaker. *)
- let create ~failure_threshold ~success_threshold ~timeout_ms : t option =
- F.proven_circuit_breaker_create
- (Unsigned.UInt32.of_int failure_threshold)
- (Unsigned.UInt32.of_int success_threshold)
- (Int64.of_int timeout_ms)
-
- (** Check whether a request should be allowed. *)
- let allow (cb : t) : bool =
- F.proven_circuit_breaker_allow cb
-
- (** Record a successful request. *)
- let success (cb : t) : unit =
- F.proven_circuit_breaker_success cb
-
- (** Record a failed request. *)
- let failure (cb : t) : unit =
- F.proven_circuit_breaker_failure cb
-
- (** Get the current circuit breaker state. *)
- let state (cb : t) : state =
- match Int32.to_int (F.proven_circuit_breaker_state cb) with
- | 0 -> Closed
- | 1 -> Open
- | 2 -> Half_open
- | _ -> Open
-
- (** Free the circuit breaker. *)
- let free (cb : t) : unit =
- F.proven_circuit_breaker_free cb
-end
-
-(* ========================================================================== *)
-(* SafeRetry *)
-(* ========================================================================== *)
-
-module SafeRetry = struct
- (** Retry configuration. *)
- type config = {
- max_attempts : int;
- base_delay_ms : int;
- max_delay_ms : int;
- multiplier : float;
- }
-
- let make_config (c : config) : F.retry_config structure =
- let rc = make F.retry_config in
- setf rc F.rc_max_attempts (Unsigned.UInt32.of_int c.max_attempts);
- setf rc F.rc_base_delay_ms (Unsigned.UInt64.of_int c.base_delay_ms);
- setf rc F.rc_max_delay_ms (Unsigned.UInt64.of_int c.max_delay_ms);
- setf rc F.rc_multiplier c.multiplier;
- rc
-
- (** Calculate the delay for a given attempt number. *)
- let delay (config : config) (attempt : int) : int =
- Unsigned.UInt64.to_int (F.proven_retry_delay (make_config config) (Unsigned.UInt32.of_int attempt))
-
- (** Check whether a retry should be attempted. *)
- let should_retry (config : config) (attempt : int) : bool =
- F.proven_retry_should_retry (make_config config) (Unsigned.UInt32.of_int attempt)
-end
-
-(* ========================================================================== *)
-(* SafeMonotonic *)
-(* ========================================================================== *)
-
-module SafeMonotonic = struct
- (** Opaque monotonic counter handle. *)
- type t = F.monotonic_counter structure ptr
-
- (** Create a monotonic counter with initial value and maximum. *)
- let create ~initial ~max_value : t option =
- F.proven_monotonic_create
- (Unsigned.UInt64.of_int initial)
- (Unsigned.UInt64.of_int max_value)
-
- (** Get the next value from the counter. Returns [None] at overflow. *)
- let next (c : t) : int64 option =
- unwrap_int_result (F.proven_monotonic_next c)
-
- (** Free the counter. *)
- let free (c : t) : unit =
- F.proven_monotonic_free c
-end
-
-(* ========================================================================== *)
-(* SafeStateMachine *)
-(* ========================================================================== *)
-
-module SafeStateMachine = struct
- (** Opaque state machine handle. *)
- type t = F.state_machine structure ptr
-
- (** Create a state machine with [state_count] states and an initial state. *)
- let create ~state_count ~initial_state : t option =
- F.proven_state_machine_create
- (Unsigned.UInt32.of_int state_count)
- (Unsigned.UInt32.of_int initial_state)
-
- (** Allow a transition from one state to another. Returns success. *)
- let allow_transition (sm : t) ~from ~to_ : bool =
- F.proven_state_machine_allow sm
- (Unsigned.UInt32.of_int from) (Unsigned.UInt32.of_int to_)
-
- (** Try to transition to a new state. Returns [true] if the transition
- was allowed and completed. *)
- let transition (sm : t) ~to_ : bool =
- F.proven_state_machine_transition sm (Unsigned.UInt32.of_int to_)
-
- (** Get the current state. *)
- let current_state (sm : t) : int =
- Unsigned.UInt32.to_int (F.proven_state_machine_state sm)
-
- (** Free the state machine. *)
- let free (sm : t) : unit =
- F.proven_state_machine_free sm
-end
-
-(* ========================================================================== *)
-(* SafeTensor *)
-(* ========================================================================== *)
-
-module SafeTensor = struct
- (** Opaque 2D tensor handle. *)
- type t = F.tensor_2d structure ptr
-
- (** Create a [rows x cols] tensor (initialized to zero). *)
- let create ~rows ~cols : t option =
- F.proven_tensor_create
- (Unsigned.Size_t.of_int rows)
- (Unsigned.Size_t.of_int cols)
-
- (** Set a value at (row, col). Returns [true] on success. *)
- let set (t : t) ~row ~col (value : float) : bool =
- let rc = F.proven_tensor_set t
- (Unsigned.Size_t.of_int row)
- (Unsigned.Size_t.of_int col) value in
- Int32.equal rc 0l
-
- (** Get a value at (row, col). *)
- let get (t : t) ~row ~col : float option =
- unwrap_float_result (F.proven_tensor_get t
- (Unsigned.Size_t.of_int row)
- (Unsigned.Size_t.of_int col))
-
- (** Matrix multiplication. Returns [None] if dimensions are incompatible. *)
- let matmul (a : t) (b : t) : t option =
- F.proven_tensor_matmul a b
-
- (** Free the tensor. *)
- let free (t : t) : unit =
- F.proven_tensor_free t
-end
-
-(* ========================================================================== *)
-(* SafeMl *)
-(* ========================================================================== *)
-
-module SafeMl = struct
- (** Sigmoid activation function. *)
- let sigmoid (x : float) : float =
- F.proven_ml_sigmoid x
-
- (** ReLU activation function. *)
- let relu (x : float) : float =
- F.proven_ml_relu x
-
- (** Leaky ReLU activation function. *)
- let leaky_relu ?(alpha = 0.01) (x : float) : float =
- F.proven_ml_leaky_relu x alpha
-
- (** Clamp value to [min_val, max_val]. *)
- let clamp ~min_val ~max_val (x : float) : float =
- F.proven_ml_clamp x min_val max_val
-end
-
-(* ========================================================================== *)
-(* SafeLru *)
-(* ========================================================================== *)
-
-module SafeLru = struct
- (** Opaque LRU cache handle. *)
- type t = F.lru_cache structure ptr
-
- (** Create an LRU cache with the given capacity. *)
- let create (capacity : int) : t option =
- F.proven_lru_create (Unsigned.Size_t.of_int capacity)
-
- (** Get a value by key. Returns [None] on miss. *)
- let get (cache : t) (key : int) : int64 option =
- unwrap_int_result (F.proven_lru_get cache (Unsigned.UInt64.of_int key))
-
- (** Put a key-value pair. Returns [true] on success. *)
- let put (cache : t) (key : int) (value : int64) : bool =
- let rc = F.proven_lru_put cache (Unsigned.UInt64.of_int key) value in
- Int32.equal rc 0l
-
- (** Free the cache. *)
- let free (cache : t) : unit =
- F.proven_lru_free cache
-end
-
-(* ========================================================================== *)
-(* SafeGraph *)
-(* ========================================================================== *)
-
-module SafeGraph = struct
- (** Opaque graph handle. *)
- type t = F.graph structure ptr
-
- (** Create a graph with the given number of nodes. *)
- let create (node_count : int) : t option =
- F.proven_graph_create (Unsigned.Size_t.of_int node_count)
-
- (** Add a directed edge. Returns [true] on success. *)
- let add_edge (g : t) ~from ~to_ : bool =
- let rc = F.proven_graph_add_edge g
- (Unsigned.Size_t.of_int from)
- (Unsigned.Size_t.of_int to_) in
- Int32.equal rc 0l
-
- (** Check whether a directed edge exists. *)
- let has_edge (g : t) ~from ~to_ : bool =
- F.proven_graph_has_edge g
- (Unsigned.Size_t.of_int from)
- (Unsigned.Size_t.of_int to_)
-
- (** Free the graph. *)
- let free (g : t) : unit =
- F.proven_graph_free g
-end
-
-(* ========================================================================== *)
-(* SafeQueue *)
-(* ========================================================================== *)
-
-module SafeQueue = struct
- (** Opaque bounded queue handle. *)
- type t = F.bounded_queue structure ptr
-
- (** Create a bounded FIFO queue with the given capacity. *)
- let create (capacity : int) : t option =
- F.proven_queue_create (Unsigned.Size_t.of_int capacity)
-
- (** Push a value. Returns [true] on success, [false] if full. *)
- let push (q : t) (value : int64) : bool =
- F.proven_queue_push q value
-
- (** Pop a value. Returns [None] if empty. *)
- let pop (q : t) : int64 option =
- unwrap_int_result (F.proven_queue_pop q)
-
- (** Get current queue size. *)
- let size (q : t) : int =
- Unsigned.Size_t.to_int (F.proven_queue_size q)
-
- (** Free the queue. *)
- let free (q : t) : unit =
- F.proven_queue_free q
-end
-
-(* ========================================================================== *)
-(* SafeBloom *)
-(* ========================================================================== *)
-
-module SafeBloom = struct
- (** Opaque bloom filter handle. *)
- type t = F.bloom_filter structure ptr
-
- (** Create a bloom filter. *)
- let create ~expected_elements ~false_positive_rate : t option =
- F.proven_bloom_create
- (Unsigned.Size_t.of_int expected_elements)
- false_positive_rate
-
- (** Add an element to the filter. *)
- let add (bf : t) (s : string) : unit =
- let p = cstring_of_string s in
- F.proven_bloom_add bf p (Unsigned.Size_t.of_int (String.length s))
-
- (** Check whether an element might be in the filter. *)
- let contains (bf : t) (s : string) : bool =
- let p = cstring_of_string s in
- F.proven_bloom_contains bf p (Unsigned.Size_t.of_int (String.length s))
-
- (** Free the bloom filter. *)
- let free (bf : t) : unit =
- F.proven_bloom_free bf
-end
-
-(* ========================================================================== *)
-(* Callbacks *)
-(* ========================================================================== *)
-
-module Callbacks = struct
- (** Event types that can trigger callbacks. *)
- type event_type =
- | Validation_failed
- | Resource_acquired
- | Resource_released
- | Rate_limit_hit
- | Circuit_state_change
- | Signal_received
- | Retry_attempt
- | Crypto_operation
- | Custom
-
- let event_type_to_int = function
- | Validation_failed -> 1l
- | Resource_acquired -> 2l
- | Resource_released -> 3l
- | Rate_limit_hit -> 4l
- | Circuit_state_change -> 5l
- | Signal_received -> 6l
- | Retry_attempt -> 7l
- | Crypto_operation -> 8l
- | Custom -> 100l
-
- (** Query how many callbacks are registered for an event type. *)
- let count (et : event_type) : int =
- Unsigned.UInt32.to_int (F.proven_callback_count (event_type_to_int et))
-
- (** Unregister all callbacks. Returns the number removed. *)
- let clear_all () : int =
- Unsigned.UInt32.to_int (F.proven_callback_clear_all ())
+ let has_crlf (s : string) : bool =
+ match has_crlf_result s with Some v -> v | None -> true
end
diff --git a/bindings/ocaml/lib/proven_ffi.ml b/bindings/ocaml/lib/proven_ffi.ml
index 1d859520..1f7df219 100644
--- a/bindings/ocaml/lib/proven_ffi.ml
+++ b/bindings/ocaml/lib/proven_ffi.ml
@@ -3,9 +3,12 @@
(** Low-level ctypes FFI bindings to libproven.
- This module declares all C-ABI types and function bindings using
- [Ctypes] and [Ctypes.Foreign]. Every function here is a direct
- 1-to-1 mapping of a [proven_*] export from the shared library.
+ Binds only symbols whose row in the C ABI status ledger
+ ([bindings/c/include/proven-abi.tsv]) is [exported]: present in
+ libproven with the signature declared in [proven.h]. Every other
+ [proven.h] function is an [owed] or [conflict] row and is deliberately
+ not bound here; binding it eagerly would make this library fail to load.
+ [scripts/full-api-audit.sh] enforces this against the real library.
Users should prefer the safe wrappers in {!Proven} instead. *)
@@ -22,7 +25,7 @@ let lib = Dl.dlopen ~filename:"libproven.so" ~flags:[Dl.RTLD_NOW; Dl.RTLD_GLOBAL
(* Enum: ProvenStatus *)
(* -------------------------------------------------------------------------- *)
-(** Status codes returned by most libproven functions. *)
+(** Status codes returned by libproven functions. *)
let proven_status_ok = 0l
let proven_status_err_null_pointer = -1l
let proven_status_err_invalid_arg = -2l
@@ -35,16 +38,6 @@ let proven_status_err_out_of_bounds = -8l
let proven_status_err_encoding = -9l
let proven_status_err_alloc_failed = -10l
-(* -------------------------------------------------------------------------- *)
-(* Struct: IntResult { status: i32, value: i64 } *)
-(* -------------------------------------------------------------------------- *)
-
-type int_result
-let int_result : int_result structure typ = structure "IntResult"
-let ir_status = field int_result "status" int32_t
-let ir_value = field int_result "value" int64_t
-let () = seal int_result
-
(* -------------------------------------------------------------------------- *)
(* Struct: BoolResult { status: i32, value: bool } *)
(* -------------------------------------------------------------------------- *)
@@ -55,302 +48,10 @@ let br_status = field bool_result "status" int32_t
let br_value = field bool_result "value" bool
let () = seal bool_result
-(* -------------------------------------------------------------------------- *)
-(* Struct: StringResult { status: i32, value: *char, length: size_t } *)
-(* -------------------------------------------------------------------------- *)
-
-type string_result
-let string_result : string_result structure typ = structure "StringResult"
-let sr_status = field string_result "status" int32_t
-let sr_value = field string_result "value" (ptr char)
-let sr_length = field string_result "length" size_t
-let () = seal string_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: FloatResult { status: i32, value: f64 } *)
-(* -------------------------------------------------------------------------- *)
-
-type float_result
-let float_result : float_result structure typ = structure "FloatResult"
-let fr_status = field float_result "status" int32_t
-let fr_value = field float_result "value" double
-let () = seal float_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: UUID { bytes: u8[16] } *)
-(* -------------------------------------------------------------------------- *)
-
-type uuid
-let uuid : uuid structure typ = structure "UUID"
-let uuid_bytes = field uuid "bytes" (array 16 uint8_t)
-let () = seal uuid
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: UUIDResult { status: i32, uuid: UUID } *)
-(* -------------------------------------------------------------------------- *)
-
-type uuid_result
-let uuid_result : uuid_result structure typ = structure "UUIDResult"
-let ur_status = field uuid_result "status" int32_t
-let ur_uuid = field uuid_result "uuid" uuid
-let () = seal uuid_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: IPv4Address { octets: u8[4] } *)
-(* -------------------------------------------------------------------------- *)
-
-type ipv4_address
-let ipv4_address : ipv4_address structure typ = structure "IPv4Address"
-let ipv4_octets = field ipv4_address "octets" (array 4 uint8_t)
-let () = seal ipv4_address
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: IPv4Result { status: i32, address: IPv4Address } *)
-(* -------------------------------------------------------------------------- *)
-
-type ipv4_result
-let ipv4_result : ipv4_result structure typ = structure "IPv4Result"
-let ipv4r_status = field ipv4_result "status" int32_t
-let ipv4r_address = field ipv4_result "address" ipv4_address
-let () = seal ipv4_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: CurrencyResult *)
-(* -------------------------------------------------------------------------- *)
-
-type currency_result
-let currency_result : currency_result structure typ = structure "CurrencyResult"
-let cur_status = field currency_result "status" int32_t
-let cur_amount_minor = field currency_result "amount_minor" int64_t
-let cur_currency_code = field currency_result "currency_code" (array 3 uint8_t)
-let cur_decimal_places = field currency_result "decimal_places" uint8_t
-let () = seal currency_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: PhoneResult *)
-(* -------------------------------------------------------------------------- *)
-
-type phone_result
-let phone_result : phone_result structure typ = structure "PhoneResult"
-let phr_status = field phone_result "status" int32_t
-let phr_country_code = field phone_result "country_code" uint16_t
-let phr_national_number = field phone_result "national_number" uint64_t
-let phr_is_valid = field phone_result "is_valid" bool
-let () = seal phone_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: DateTime *)
-(* -------------------------------------------------------------------------- *)
-
-type datetime
-let datetime : datetime structure typ = structure "DateTime"
-let dt_year = field datetime "year" int32_t
-let dt_month = field datetime "month" uint8_t
-let dt_day = field datetime "day" uint8_t
-let dt_hour = field datetime "hour" uint8_t
-let dt_minute = field datetime "minute" uint8_t
-let dt_second = field datetime "second" uint8_t
-let dt_nanosecond = field datetime "nanosecond" uint32_t
-let dt_tz_offset_minutes = field datetime "tz_offset_minutes" int16_t
-let () = seal datetime
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: DateTimeResult *)
-(* -------------------------------------------------------------------------- *)
-
-type datetime_result
-let datetime_result : datetime_result structure typ = structure "DateTimeResult"
-let dtr_status = field datetime_result "status" int32_t
-let dtr_datetime = field datetime_result "datetime" datetime
-let () = seal datetime_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: SemanticVersion *)
-(* -------------------------------------------------------------------------- *)
-
-type semantic_version
-let semantic_version : semantic_version structure typ = structure "SemanticVersion"
-let sv_major = field semantic_version "major" uint32_t
-let sv_minor = field semantic_version "minor" uint32_t
-let sv_patch = field semantic_version "patch" uint32_t
-let sv_prerelease_len = field semantic_version "prerelease_len" size_t
-let sv_prerelease = field semantic_version "prerelease" (ptr char)
-let () = seal semantic_version
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: VersionResult *)
-(* -------------------------------------------------------------------------- *)
-
-type version_result
-let version_result : version_result structure typ = structure "VersionResult"
-let vr_status = field version_result "status" int32_t
-let vr_version = field version_result "version" semantic_version
-let () = seal version_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: GeoCoordinate *)
-(* -------------------------------------------------------------------------- *)
-
-type geo_coordinate
-let geo_coordinate : geo_coordinate structure typ = structure "GeoCoordinate"
-let geo_latitude = field geo_coordinate "latitude" double
-let geo_longitude = field geo_coordinate "longitude" double
-let () = seal geo_coordinate
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: GeoResult *)
-(* -------------------------------------------------------------------------- *)
-
-type geo_result
-let geo_result : geo_result structure typ = structure "GeoResult"
-let geor_status = field geo_result "status" int32_t
-let geor_coordinate = field geo_result "coordinate" geo_coordinate
-let () = seal geo_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: PasswordResult *)
-(* -------------------------------------------------------------------------- *)
-
-type password_result
-let password_result : password_result structure typ = structure "PasswordResult"
-let pw_strength = field password_result "strength" int32_t
-let pw_has_lowercase = field password_result "has_lowercase" bool
-let pw_has_uppercase = field password_result "has_uppercase" bool
-let pw_has_digit = field password_result "has_digit" bool
-let pw_has_special = field password_result "has_special" bool
-let pw_length = field password_result "length" size_t
-let () = seal password_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: RGBColor *)
-(* -------------------------------------------------------------------------- *)
-
-type rgb_color
-let rgb_color : rgb_color structure typ = structure "RGBColor"
-let rgb_r = field rgb_color "r" uint8_t
-let rgb_g = field rgb_color "g" uint8_t
-let rgb_b = field rgb_color "b" uint8_t
-let () = seal rgb_color
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: HSLColor *)
-(* -------------------------------------------------------------------------- *)
-
-type hsl_color
-let hsl_color : hsl_color structure typ = structure "HSLColor"
-let hsl_h = field hsl_color "h" double
-let hsl_s = field hsl_color "s" double
-let hsl_l = field hsl_color "l" double
-let () = seal hsl_color
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: ColorParseResult *)
-(* -------------------------------------------------------------------------- *)
-
-type color_parse_result
-let color_parse_result : color_parse_result structure typ = structure "ColorParseResult"
-let cpr_status = field color_parse_result "status" int32_t
-let cpr_color = field color_parse_result "color" rgb_color
-let () = seal color_parse_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: HexDecodeResult *)
-(* -------------------------------------------------------------------------- *)
-
-type hex_decode_result
-let hex_decode_result : hex_decode_result structure typ = structure "HexDecodeResult"
-let hdr_status = field hex_decode_result "status" int32_t
-let hdr_data = field hex_decode_result "data" (ptr uint8_t)
-let hdr_length = field hex_decode_result "length" size_t
-let () = seal hex_decode_result
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: RetryConfig *)
-(* -------------------------------------------------------------------------- *)
-
-type retry_config
-let retry_config : retry_config structure typ = structure "RetryConfig"
-let rc_max_attempts = field retry_config "max_attempts" uint32_t
-let rc_base_delay_ms = field retry_config "base_delay_ms" uint64_t
-let rc_max_delay_ms = field retry_config "max_delay_ms" uint64_t
-let rc_multiplier = field retry_config "multiplier" double
-let () = seal retry_config
-
-(* -------------------------------------------------------------------------- *)
-(* Opaque pointer types for stateful objects *)
-(* -------------------------------------------------------------------------- *)
-
-(* Keep pointee types incomplete. Sealing an empty C struct is unsupported;
- these declarations are used only behind pointers, never allocated here. *)
-
-(** Opaque handle for BoundedBuffer. *)
-type bounded_buffer
-let bounded_buffer : bounded_buffer structure typ = structure "BoundedBuffer"
-
-(** Opaque handle for RateLimiter. *)
-type rate_limiter
-let rate_limiter : rate_limiter structure typ = structure "RateLimiter"
-
-(** Opaque handle for CircuitBreaker. *)
-type circuit_breaker
-let circuit_breaker : circuit_breaker structure typ = structure "CircuitBreaker"
-
-(** Opaque handle for MonotonicCounter. *)
-type monotonic_counter
-let monotonic_counter : monotonic_counter structure typ = structure "MonotonicCounter"
-
-(** Opaque handle for StateMachine. *)
-type state_machine
-let state_machine : state_machine structure typ = structure "StateMachine"
-
-(** Opaque handle for Tensor2D. *)
-type tensor_2d
-let tensor_2d : tensor_2d structure typ = structure "Tensor2D"
-
-(** Opaque handle for LRUCache. *)
-type lru_cache
-let lru_cache : lru_cache structure typ = structure "LRUCache"
-
-(** Opaque handle for Graph. *)
-type graph
-let graph : graph structure typ = structure "Graph"
-
-(** Opaque handle for BoundedQueue. *)
-type bounded_queue
-let bounded_queue : bounded_queue structure typ = structure "BoundedQueue"
-
-(** Opaque handle for BloomFilter. *)
-type bloom_filter
-let bloom_filter : bloom_filter structure typ = structure "BloomFilter"
-
-(* -------------------------------------------------------------------------- *)
-(* Struct: BufferResult { status: i32, buffer: *BoundedBuffer } *)
-(* -------------------------------------------------------------------------- *)
-
-type buffer_result
-let buffer_result : buffer_result structure typ = structure "BufferResult"
-let bufr_status = field buffer_result "status" int32_t
-let bufr_buffer = field buffer_result "buffer" (ptr bounded_buffer)
-let () = seal buffer_result
-
(* ========================================================================== *)
-(* Function bindings *)
+(* Function bindings: ledger status `exported` *)
(* ========================================================================== *)
-(* -- Lifecycle ------------------------------------------------------------- *)
-
-let proven_init =
- foreign ~from:lib "proven_init"
- (void @-> returning int32_t)
-
-let proven_deinit =
- foreign ~from:lib "proven_deinit"
- (void @-> returning void)
-
-let proven_is_initialized =
- foreign ~from:lib "proven_is_initialized"
- (void @-> returning bool)
-
(* -- Memory management ----------------------------------------------------- *)
let proven_free_string =
@@ -375,649 +76,14 @@ let proven_ffi_abi_version =
foreign ~from:lib "proven_ffi_abi_version"
(void @-> returning uint32_t)
-let proven_module_count =
- foreign ~from:lib "proven_module_count"
- (void @-> returning uint32_t)
-
-(* -- SafeMath -------------------------------------------------------------- *)
-
-let proven_math_div =
- foreign ~from:lib "proven_math_div"
- (int64_t @-> int64_t @-> returning int_result)
-
-let proven_math_mod =
- foreign ~from:lib "proven_math_mod"
- (int64_t @-> int64_t @-> returning int_result)
-
-let proven_math_add_checked =
- foreign ~from:lib "proven_math_add_checked"
- (int64_t @-> int64_t @-> returning int_result)
-
-let proven_math_sub_checked =
- foreign ~from:lib "proven_math_sub_checked"
- (int64_t @-> int64_t @-> returning int_result)
-
-let proven_math_mul_checked =
- foreign ~from:lib "proven_math_mul_checked"
- (int64_t @-> int64_t @-> returning int_result)
-
-let proven_math_abs_safe =
- foreign ~from:lib "proven_math_abs_safe"
- (int64_t @-> returning int_result)
-
-let proven_math_clamp =
- foreign ~from:lib "proven_math_clamp"
- (int64_t @-> int64_t @-> int64_t @-> returning int64_t)
-
-let proven_math_pow_checked =
- foreign ~from:lib "proven_math_pow_checked"
- (int64_t @-> uint32_t @-> returning int_result)
-
-(* -- SafeString ------------------------------------------------------------ *)
-
-let proven_string_is_valid_utf8 =
- foreign ~from:lib "proven_string_is_valid_utf8"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_string_escape_sql =
- foreign ~from:lib "proven_string_escape_sql"
- (ptr char @-> size_t @-> returning string_result)
-
-let proven_string_escape_html =
- foreign ~from:lib "proven_string_escape_html"
- (ptr char @-> size_t @-> returning string_result)
-
-let proven_string_escape_js =
- foreign ~from:lib "proven_string_escape_js"
- (ptr char @-> size_t @-> returning string_result)
-
-(* -- SafePath -------------------------------------------------------------- *)
+(* -- SafePath (zig-legacy backend) ----------------------------------------- *)
let proven_path_has_traversal =
foreign ~from:lib "proven_path_has_traversal"
(ptr char @-> size_t @-> returning bool_result)
-let proven_path_sanitize_filename =
- foreign ~from:lib "proven_path_sanitize_filename"
- (ptr char @-> size_t @-> returning string_result)
-
-(* -- SafeCrypto ------------------------------------------------------------ *)
-
-let proven_crypto_constant_time_eq =
- foreign ~from:lib "proven_crypto_constant_time_eq"
- (ptr char @-> size_t @-> ptr char @-> size_t @-> returning bool_result)
-
-let proven_crypto_random_bytes =
- foreign ~from:lib "proven_crypto_random_bytes"
- (ptr char @-> size_t @-> returning int32_t)
-
-(* -- SafeUrl --------------------------------------------------------------- *)
-
-(* Note: URL parsing uses a complex struct; we wrap only the simpler
- helpers at this level. Full URL parsing is available through the
- proven_url_parse / proven_url_free pair if needed. *)
-
-(* -- SafeEmail ------------------------------------------------------------- *)
-
-let proven_email_is_valid =
- foreign ~from:lib "proven_email_is_valid"
- (ptr char @-> size_t @-> returning bool_result)
-
-(* -- SafeNetwork ----------------------------------------------------------- *)
-
-let proven_network_parse_ipv4 =
- foreign ~from:lib "proven_network_parse_ipv4"
- (ptr char @-> size_t @-> returning ipv4_result)
-
-let proven_network_ipv4_is_private =
- foreign ~from:lib "proven_network_ipv4_is_private"
- (ipv4_address @-> returning bool)
-
-let proven_network_ipv4_is_loopback =
- foreign ~from:lib "proven_network_ipv4_is_loopback"
- (ipv4_address @-> returning bool)
-
-(* -- SafeHeader ------------------------------------------------------------ *)
+(* -- SafeHeader (idris-refc backend) --------------------------------------- *)
let proven_header_has_crlf =
foreign ~from:lib "proven_header_has_crlf"
(ptr char @-> size_t @-> returning bool_result)
-
-let proven_header_is_valid_name =
- foreign ~from:lib "proven_header_is_valid_name"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_header_is_dangerous =
- foreign ~from:lib "proven_header_is_dangerous"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_header_render =
- foreign ~from:lib "proven_header_render"
- (ptr char @-> size_t @-> ptr char @-> size_t @-> returning string_result)
-
-let proven_header_build_csp =
- foreign ~from:lib "proven_header_build_csp"
- (ptr char @-> size_t @-> returning string_result)
-
-let proven_header_build_hsts =
- foreign ~from:lib "proven_header_build_hsts"
- (int64_t @-> bool @-> bool @-> returning string_result)
-
-(* -- SafeCookie ------------------------------------------------------------ *)
-
-let proven_cookie_has_injection =
- foreign ~from:lib "proven_cookie_has_injection"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_cookie_validate_name =
- foreign ~from:lib "proven_cookie_validate_name"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_cookie_validate_value =
- foreign ~from:lib "proven_cookie_validate_value"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_cookie_get_prefix =
- foreign ~from:lib "proven_cookie_get_prefix"
- (ptr char @-> size_t @-> returning int_result)
-
-let proven_cookie_build_delete =
- foreign ~from:lib "proven_cookie_build_delete"
- (ptr char @-> size_t @-> returning string_result)
-
-(* -- SafeContentType ------------------------------------------------------- *)
-
-let proven_content_type_can_sniff_dangerous =
- foreign ~from:lib "proven_content_type_can_sniff_dangerous"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_content_type_is_json =
- foreign ~from:lib "proven_content_type_is_json"
- (ptr char @-> size_t @-> ptr char @-> size_t @-> returning bool_result)
-
-let proven_content_type_is_xml =
- foreign ~from:lib "proven_content_type_is_xml"
- (ptr char @-> size_t @-> ptr char @-> size_t @-> returning bool_result)
-
-(* -- SafeUUID -------------------------------------------------------------- *)
-
-let proven_uuid_v4 =
- foreign ~from:lib "proven_uuid_v4"
- (void @-> returning uuid_result)
-
-let proven_uuid_to_string =
- foreign ~from:lib "proven_uuid_to_string"
- (uuid @-> returning string_result)
-
-let proven_uuid_parse =
- foreign ~from:lib "proven_uuid_parse"
- (ptr char @-> size_t @-> returning uuid_result)
-
-let proven_uuid_is_nil =
- foreign ~from:lib "proven_uuid_is_nil"
- (uuid @-> returning bool)
-
-let proven_uuid_version =
- foreign ~from:lib "proven_uuid_version"
- (uuid @-> returning uint8_t)
-
-(* -- SafeJson -------------------------------------------------------------- *)
-
-let proven_json_is_valid =
- foreign ~from:lib "proven_json_is_valid"
- (ptr char @-> size_t @-> returning bool_result)
-
-let proven_json_get_type =
- foreign ~from:lib "proven_json_get_type"
- (ptr char @-> size_t @-> returning int32_t)
-
-(* -- SafeDateTime ---------------------------------------------------------- *)
-
-let proven_datetime_parse =
- foreign ~from:lib "proven_datetime_parse"
- (ptr char @-> size_t @-> returning datetime_result)
-
-let proven_datetime_format_iso8601 =
- foreign ~from:lib "proven_datetime_format_iso8601"
- (datetime @-> returning string_result)
-
-let proven_datetime_is_leap_year =
- foreign ~from:lib "proven_datetime_is_leap_year"
- (int32_t @-> returning bool)
-
-let proven_datetime_days_in_month =
- foreign ~from:lib "proven_datetime_days_in_month"
- (int32_t @-> uint8_t @-> returning uint8_t)
-
-(* -- SafeFloat ------------------------------------------------------------- *)
-
-let proven_float_div =
- foreign ~from:lib "proven_float_div"
- (double @-> double @-> returning float_result)
-
-let proven_float_is_finite =
- foreign ~from:lib "proven_float_is_finite"
- (double @-> returning bool)
-
-let proven_float_is_nan =
- foreign ~from:lib "proven_float_is_nan"
- (double @-> returning bool)
-
-let proven_float_sqrt =
- foreign ~from:lib "proven_float_sqrt"
- (double @-> returning float_result)
-
-let proven_float_ln =
- foreign ~from:lib "proven_float_ln"
- (double @-> returning float_result)
-
-(* -- SafePassword ---------------------------------------------------------- *)
-
-let proven_password_validate =
- foreign ~from:lib "proven_password_validate"
- (ptr char @-> size_t @-> returning password_result)
-
-let proven_password_is_common =
- foreign ~from:lib "proven_password_is_common"
- (ptr char @-> size_t @-> returning bool)
-
-(* -- SafeVersion ----------------------------------------------------------- *)
-
-let proven_version_parse_semver =
- foreign ~from:lib "proven_version_parse"
- (ptr char @-> size_t @-> returning version_result)
-
-let proven_version_compare =
- foreign ~from:lib "proven_version_compare"
- (semantic_version @-> semantic_version @-> returning int32_t)
-
-let proven_version_free =
- foreign ~from:lib "proven_version_free"
- (ptr semantic_version @-> returning void)
-
-(* -- SafeGeo --------------------------------------------------------------- *)
-
-let proven_geo_validate =
- foreign ~from:lib "proven_geo_validate"
- (double @-> double @-> returning geo_result)
-
-let proven_geo_distance =
- foreign ~from:lib "proven_geo_distance"
- (geo_coordinate @-> geo_coordinate @-> returning float_result)
-
-let proven_geo_in_bounds =
- foreign ~from:lib "proven_geo_in_bounds"
- (geo_coordinate @-> double @-> double @-> double @-> double @-> returning bool)
-
-(* -- SafeChecksum ---------------------------------------------------------- *)
-
-let proven_checksum_crc32 =
- foreign ~from:lib "proven_checksum_crc32"
- (ptr char @-> size_t @-> returning int_result)
-
-let proven_checksum_verify_crc32 =
- foreign ~from:lib "proven_checksum_verify_crc32"
- (ptr char @-> size_t @-> uint32_t @-> returning bool_result)
-
-(* -- SafeProbability ------------------------------------------------------- *)
-
-let proven_probability_create =
- foreign ~from:lib "proven_probability_create"
- (double @-> returning double)
-
-let proven_probability_and =
- foreign ~from:lib "proven_probability_and"
- (double @-> double @-> returning double)
-
-let proven_probability_or_exclusive =
- foreign ~from:lib "proven_probability_or_exclusive"
- (double @-> double @-> returning double)
-
-let proven_probability_not =
- foreign ~from:lib "proven_probability_not"
- (double @-> returning double)
-
-(* -- SafeCalculator -------------------------------------------------------- *)
-
-let proven_calculator_eval =
- foreign ~from:lib "proven_calculator_eval"
- (ptr char @-> size_t @-> returning float_result)
-
-(* -- SafeHex --------------------------------------------------------------- *)
-
-let proven_hex_encode =
- foreign ~from:lib "proven_hex_encode"
- (ptr char @-> size_t @-> bool @-> returning string_result)
-
-let proven_hex_decode =
- foreign ~from:lib "proven_hex_decode"
- (ptr char @-> size_t @-> returning hex_decode_result)
-
-let proven_hex_free =
- foreign ~from:lib "proven_hex_free"
- (ptr hex_decode_result @-> returning void)
-
-(* -- SafeCurrency ---------------------------------------------------------- *)
-
-let proven_currency_parse =
- foreign ~from:lib "proven_currency_parse"
- (ptr char @-> size_t @-> returning currency_result)
-
-let proven_currency_format =
- foreign ~from:lib "proven_currency_format"
- (int64_t @-> array 3 uint8_t @-> uint8_t @-> returning string_result)
-
-(* -- SafePhone ------------------------------------------------------------- *)
-
-let proven_phone_parse =
- foreign ~from:lib "proven_phone_parse"
- (ptr char @-> size_t @-> returning phone_result)
-
-let proven_phone_format_e164 =
- foreign ~from:lib "proven_phone_format_e164"
- (uint16_t @-> uint64_t @-> returning string_result)
-
-(* -- SafeColor ------------------------------------------------------------- *)
-
-let proven_color_parse_hex =
- foreign ~from:lib "proven_color_parse_hex"
- (ptr char @-> size_t @-> returning color_parse_result)
-
-let proven_color_rgb_to_hsl =
- foreign ~from:lib "proven_color_rgb_to_hsl"
- (rgb_color @-> returning hsl_color)
-
-let proven_color_to_hex =
- foreign ~from:lib "proven_color_to_hex"
- (rgb_color @-> returning string_result)
-
-(* -- SafeAngle ------------------------------------------------------------- *)
-
-let proven_angle_deg_to_rad =
- foreign ~from:lib "proven_angle_deg_to_rad"
- (double @-> returning double)
-
-let proven_angle_rad_to_deg =
- foreign ~from:lib "proven_angle_rad_to_deg"
- (double @-> returning double)
-
-let proven_angle_normalize_degrees =
- foreign ~from:lib "proven_angle_normalize_degrees"
- (double @-> returning double)
-
-let proven_angle_normalize_radians =
- foreign ~from:lib "proven_angle_normalize_radians"
- (double @-> returning double)
-
-(* -- SafeUnit -------------------------------------------------------------- *)
-
-let proven_unit_convert_length =
- foreign ~from:lib "proven_unit_convert_length"
- (double @-> int32_t @-> int32_t @-> returning float_result)
-
-let proven_unit_convert_temp =
- foreign ~from:lib "proven_unit_convert_temp"
- (double @-> int32_t @-> int32_t @-> returning float_result)
-
-(* -- SafeHttp -------------------------------------------------------------- *)
-
-let proven_http_url_encode =
- foreign ~from:lib "proven_http_url_encode"
- (ptr char @-> size_t @-> returning string_result)
-
-let proven_http_url_decode =
- foreign ~from:lib "proven_http_url_decode"
- (ptr char @-> size_t @-> returning string_result)
-
-(* -- SafeBuffer ------------------------------------------------------------ *)
-
-let proven_buffer_create =
- foreign ~from:lib "proven_buffer_create"
- (size_t @-> returning buffer_result)
-
-let proven_buffer_append =
- foreign ~from:lib "proven_buffer_append"
- (ptr bounded_buffer @-> ptr char @-> size_t @-> returning int32_t)
-
-let proven_buffer_get =
- foreign ~from:lib "proven_buffer_get"
- (ptr bounded_buffer @-> ptr (ptr char) @-> ptr size_t @-> returning int32_t)
-
-let proven_buffer_free =
- foreign ~from:lib "proven_buffer_free"
- (ptr bounded_buffer @-> returning void)
-
-(* -- SafeRateLimiter ------------------------------------------------------- *)
-
-let proven_rate_limiter_create =
- foreign ~from:lib "proven_rate_limiter_create"
- (double @-> double @-> returning (ptr_opt rate_limiter))
-
-let proven_rate_limiter_try_acquire =
- foreign ~from:lib "proven_rate_limiter_try_acquire"
- (ptr rate_limiter @-> double @-> returning bool)
-
-let proven_rate_limiter_free =
- foreign ~from:lib "proven_rate_limiter_free"
- (ptr rate_limiter @-> returning void)
-
-(* -- SafeCircuitBreaker ---------------------------------------------------- *)
-
-let proven_circuit_breaker_create =
- foreign ~from:lib "proven_circuit_breaker_create"
- (uint32_t @-> uint32_t @-> int64_t @-> returning (ptr_opt circuit_breaker))
-
-let proven_circuit_breaker_allow =
- foreign ~from:lib "proven_circuit_breaker_allow"
- (ptr circuit_breaker @-> returning bool)
-
-let proven_circuit_breaker_success =
- foreign ~from:lib "proven_circuit_breaker_success"
- (ptr circuit_breaker @-> returning void)
-
-let proven_circuit_breaker_failure =
- foreign ~from:lib "proven_circuit_breaker_failure"
- (ptr circuit_breaker @-> returning void)
-
-let proven_circuit_breaker_state =
- foreign ~from:lib "proven_circuit_breaker_state"
- (ptr circuit_breaker @-> returning int32_t)
-
-let proven_circuit_breaker_free =
- foreign ~from:lib "proven_circuit_breaker_free"
- (ptr circuit_breaker @-> returning void)
-
-(* -- SafeRetry ------------------------------------------------------------- *)
-
-let proven_retry_delay =
- foreign ~from:lib "proven_retry_delay"
- (retry_config @-> uint32_t @-> returning uint64_t)
-
-let proven_retry_should_retry =
- foreign ~from:lib "proven_retry_should_retry"
- (retry_config @-> uint32_t @-> returning bool)
-
-(* -- SafeMonotonic --------------------------------------------------------- *)
-
-let proven_monotonic_create =
- foreign ~from:lib "proven_monotonic_create"
- (uint64_t @-> uint64_t @-> returning (ptr_opt monotonic_counter))
-
-let proven_monotonic_next =
- foreign ~from:lib "proven_monotonic_next"
- (ptr monotonic_counter @-> returning int_result)
-
-let proven_monotonic_free =
- foreign ~from:lib "proven_monotonic_free"
- (ptr monotonic_counter @-> returning void)
-
-(* -- SafeStateMachine ------------------------------------------------------ *)
-
-let proven_state_machine_create =
- foreign ~from:lib "proven_state_machine_create"
- (uint32_t @-> uint32_t @-> returning (ptr_opt state_machine))
-
-let proven_state_machine_allow =
- foreign ~from:lib "proven_state_machine_allow"
- (ptr state_machine @-> uint32_t @-> uint32_t @-> returning bool)
-
-let proven_state_machine_transition =
- foreign ~from:lib "proven_state_machine_transition"
- (ptr state_machine @-> uint32_t @-> returning bool)
-
-let proven_state_machine_state =
- foreign ~from:lib "proven_state_machine_state"
- (ptr state_machine @-> returning uint32_t)
-
-let proven_state_machine_free =
- foreign ~from:lib "proven_state_machine_free"
- (ptr state_machine @-> returning void)
-
-(* -- SafeTensor ------------------------------------------------------------ *)
-
-let proven_tensor_create =
- foreign ~from:lib "proven_tensor_create"
- (size_t @-> size_t @-> returning (ptr_opt tensor_2d))
-
-let proven_tensor_set =
- foreign ~from:lib "proven_tensor_set"
- (ptr tensor_2d @-> size_t @-> size_t @-> double @-> returning int32_t)
-
-let proven_tensor_get =
- foreign ~from:lib "proven_tensor_get"
- (ptr tensor_2d @-> size_t @-> size_t @-> returning float_result)
-
-let proven_tensor_matmul =
- foreign ~from:lib "proven_tensor_matmul"
- (ptr tensor_2d @-> ptr tensor_2d @-> returning (ptr_opt tensor_2d))
-
-let proven_tensor_free =
- foreign ~from:lib "proven_tensor_free"
- (ptr tensor_2d @-> returning void)
-
-(* -- SafeML ---------------------------------------------------------------- *)
-
-let proven_ml_sigmoid =
- foreign ~from:lib "proven_ml_sigmoid"
- (double @-> returning double)
-
-let proven_ml_relu =
- foreign ~from:lib "proven_ml_relu"
- (double @-> returning double)
-
-let proven_ml_leaky_relu =
- foreign ~from:lib "proven_ml_leaky_relu"
- (double @-> double @-> returning double)
-
-let proven_ml_clamp =
- foreign ~from:lib "proven_ml_clamp"
- (double @-> double @-> double @-> returning double)
-
-(* -- SafeLRU --------------------------------------------------------------- *)
-
-let proven_lru_create =
- foreign ~from:lib "proven_lru_create"
- (size_t @-> returning (ptr_opt lru_cache))
-
-let proven_lru_get =
- foreign ~from:lib "proven_lru_get"
- (ptr lru_cache @-> uint64_t @-> returning int_result)
-
-let proven_lru_put =
- foreign ~from:lib "proven_lru_put"
- (ptr lru_cache @-> uint64_t @-> int64_t @-> returning int32_t)
-
-let proven_lru_free =
- foreign ~from:lib "proven_lru_free"
- (ptr lru_cache @-> returning void)
-
-(* -- SafeGraph ------------------------------------------------------------- *)
-
-let proven_graph_create =
- foreign ~from:lib "proven_graph_create"
- (size_t @-> returning (ptr_opt graph))
-
-let proven_graph_add_edge =
- foreign ~from:lib "proven_graph_add_edge"
- (ptr graph @-> size_t @-> size_t @-> returning int32_t)
-
-let proven_graph_has_edge =
- foreign ~from:lib "proven_graph_has_edge"
- (ptr graph @-> size_t @-> size_t @-> returning bool)
-
-let proven_graph_free =
- foreign ~from:lib "proven_graph_free"
- (ptr graph @-> returning void)
-
-(* -- SafeQueue ------------------------------------------------------------- *)
-
-let proven_queue_create =
- foreign ~from:lib "proven_queue_create"
- (size_t @-> returning (ptr_opt bounded_queue))
-
-let proven_queue_push =
- foreign ~from:lib "proven_queue_push"
- (ptr bounded_queue @-> int64_t @-> returning bool)
-
-let proven_queue_pop =
- foreign ~from:lib "proven_queue_pop"
- (ptr bounded_queue @-> returning int_result)
-
-let proven_queue_size =
- foreign ~from:lib "proven_queue_size"
- (ptr bounded_queue @-> returning size_t)
-
-let proven_queue_free =
- foreign ~from:lib "proven_queue_free"
- (ptr bounded_queue @-> returning void)
-
-(* -- SafeBloom ------------------------------------------------------------- *)
-
-let proven_bloom_create =
- foreign ~from:lib "proven_bloom_create"
- (size_t @-> double @-> returning (ptr_opt bloom_filter))
-
-let proven_bloom_add =
- foreign ~from:lib "proven_bloom_add"
- (ptr bloom_filter @-> ptr char @-> size_t @-> returning void)
-
-let proven_bloom_contains =
- foreign ~from:lib "proven_bloom_contains"
- (ptr bloom_filter @-> ptr char @-> size_t @-> returning bool)
-
-let proven_bloom_free =
- foreign ~from:lib "proven_bloom_free"
- (ptr bloom_filter @-> returning void)
-
-(* -- Callbacks ------------------------------------------------------------- *)
-
-let proven_callback_register =
- foreign ~from:lib "proven_callback_register"
- (int32_t @-> ptr void @-> ptr_opt void @-> returning uint32_t)
-
-let proven_callback_unregister =
- foreign ~from:lib "proven_callback_unregister"
- (uint32_t @-> returning int32_t)
-
-let proven_callback_fire =
- foreign ~from:lib "proven_callback_fire"
- (int32_t @-> ptr_opt char @-> size_t @-> int32_t @-> returning int32_t)
-
-let proven_callback_count =
- foreign ~from:lib "proven_callback_count"
- (int32_t @-> returning uint32_t)
-
-let proven_callback_clear_all =
- foreign ~from:lib "proven_callback_clear_all"
- (void @-> returning uint32_t)
-
-(* -- SafeRegistry ---------------------------------------------------------- *)
-
-(* Note: Registry and Digest use complex structs with internal pointers.
- We provide the simpler interfaces here; full parsing can be added
- by extending the struct definitions above. *)
-
-(* -- SafeDigest ------------------------------------------------------------ *)
-
-(* Digest structs with internal pointers require careful lifetime management.
- Basic operations are exposed via the string-based API through SafeHex. *)
diff --git a/bindings/ocaml/scripts/full-api-audit.sh b/bindings/ocaml/scripts/full-api-audit.sh
index 6efc7dc1..11241759 100644
--- a/bindings/ocaml/scripts/full-api-audit.sh
+++ b/bindings/ocaml/scripts/full-api-audit.sh
@@ -1,28 +1,47 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2026 Jonathan D.A. Jewell
+#
+# Full-API audit for the eager OCaml binding against the C ABI status ledger
+# (proven-abi.tsv beside proven.h) and a real libproven.so.
+#
+# Fails when the binding binds a symbol that is not a ledger `exported` row,
+# a bound symbol is absent from the library, a ledger `exported` row is
+# absent from the library, or a ledger `owed` row is present in it (the
+# ledger is stale and must be reclassified together with the code).
+# Presence alone does not prove a C signature, ownership contract or Idris
+# implementation; full_api_probe stays as the load test.
set -euo pipefail
unset CDPATH
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
: "${PROVEN_LIB_PATH:?directory containing the actual libproven.so required}"
+include=${PROVEN_INCLUDE_PATH:-"$root/../c/include"}
library="$PROVEN_LIB_PATH/libproven.so"
+ledger="$include/proven-abi.tsv"
test -s "$library"
+test -s "$ledger"
out="$root/_build/full-api-audit"
mkdir -p "$out"
echo INCOMPLETE > "$out/result.txt"
trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; fi' EXIT
-# This inventory is distinct from the five-symbol qualified wired manifest.
-# Every eagerly bound symbol must exist. Presence alone does not prove a C
-# signature, ownership contract, or Idris implementation; full_api_probe stays.
sed -nE 's/.*foreign ~from:lib "([^"]+)".*/\1/p' "$root/lib/proven_ffi.ml" | sort -u > "$out/required.txt"
test -s "$out/required.txt"
+grep -vE '^(#|[[:space:]]*$)' "$ledger" | awk -F'\t' '$2 == "exported" { print $1 }' | sort -u > "$out/ledger-exported.txt"
+grep -vE '^(#|[[:space:]]*$)' "$ledger" | awk -F'\t' '$2 == "owed" { print $1 }' | sort -u > "$out/ledger-owed.txt"
+test -s "$out/ledger-exported.txt"
nm -D --defined-only "$library" | awk '$2 ~ /^[TW]$/ {print $3}' | sort -u > "$out/exported.txt"
+comm -23 "$out/required.txt" "$out/ledger-exported.txt" > "$out/bound-not-ledger-exported.txt"
comm -23 "$out/required.txt" "$out/exported.txt" > "$out/missing.txt"
+comm -23 "$out/ledger-exported.txt" "$out/exported.txt" > "$out/ledger-exported-missing.txt"
+comm -12 "$out/ledger-owed.txt" "$out/exported.txt" > "$out/owed-present.txt"
comm -12 "$out/required.txt" "$out/exported.txt" > "$out/present.txt"
-sha256sum "$root/lib/proven_ffi.ml" "$library" > "$out/identity.sha256"
-printf 'Required=%s Present=%s Missing=%s\n' "$(wc -l < "$out/required.txt")" \
- "$(wc -l < "$out/present.txt")" "$(wc -l < "$out/missing.txt")" | tee "$out/summary.txt"
-if [[ -s "$out/missing.txt" ]]; then
- cat "$out/missing.txt"; exit 1
-fi
+sha256sum "$root/lib/proven_ffi.ml" "$ledger" "$library" > "$out/identity.sha256"
+printf 'Required=%s Present=%s Missing=%s LedgerExported=%s LedgerOwed=%s\n' \
+ "$(wc -l < "$out/required.txt")" "$(wc -l < "$out/present.txt")" "$(wc -l < "$out/missing.txt")" \
+ "$(wc -l < "$out/ledger-exported.txt")" "$(wc -l < "$out/ledger-owed.txt")" | tee "$out/summary.txt"
+fail=0
+for f in bound-not-ledger-exported missing ledger-exported-missing owed-present; do
+ if [[ -s "$out/$f.txt" ]]; then echo "FAIL: $f"; sed 's/^/ /' "$out/$f.txt"; fail=1; fi
+done
+((fail == 0))
echo PASS > "$out/result.txt"
diff --git a/bindings/ocaml/test/test_proven.ml b/bindings/ocaml/test/test_proven.ml
index 9c5c6984..36cff516 100644
--- a/bindings/ocaml/test/test_proven.ml
+++ b/bindings/ocaml/test/test_proven.ml
@@ -4,75 +4,9 @@
(** Tests for the Proven OCaml FFI bindings.
These tests call through to libproven via ctypes. They require
- [libproven.so] to be loadable at runtime (e.g., via LD_LIBRARY_PATH). *)
-
-(* -------------------------------------------------------------------------- *)
-(* Test helpers *)
-(* -------------------------------------------------------------------------- *)
-
-let option_int = Alcotest.(option int)
-let option_string = Alcotest.(option string)
-let option_float = Alcotest.(option (float 1e-6))
-
-(* -------------------------------------------------------------------------- *)
-(* Lifecycle *)
-(* -------------------------------------------------------------------------- *)
-
-let test_init () =
- let ok = Proven.Lifecycle.init () in
- Alcotest.(check bool) "init succeeds" true ok;
- Alcotest.(check bool) "is_initialized" true (Proven.Lifecycle.is_initialized ())
-
-(* -------------------------------------------------------------------------- *)
-(* SafeMath *)
-(* -------------------------------------------------------------------------- *)
-
-let test_math_div () =
- Alcotest.(check option_int) "10/2=5" (Some 5) (Proven.SafeMath.div 10 2);
- Alcotest.(check option_int) "10/0=None" None (Proven.SafeMath.div 10 0)
-
-let test_math_mod () =
- Alcotest.(check option_int) "10%3=1" (Some 1) (Proven.SafeMath.modulo 10 3);
- Alcotest.(check option_int) "10%0=None" None (Proven.SafeMath.modulo 10 0)
-
-let test_math_add () =
- Alcotest.(check option_int) "1+2=3" (Some 3) (Proven.SafeMath.add 1 2)
-
-let test_math_sub () =
- Alcotest.(check option_int) "5-3=2" (Some 2) (Proven.SafeMath.sub 5 3)
-
-let test_math_mul () =
- Alcotest.(check option_int) "3*4=12" (Some 12) (Proven.SafeMath.mul 3 4)
-
-let test_math_abs () =
- Alcotest.(check option_int) "abs(-7)=7" (Some 7) (Proven.SafeMath.abs (-7));
- Alcotest.(check option_int) "abs(0)=0" (Some 0) (Proven.SafeMath.abs 0)
-
-let test_math_clamp () =
- Alcotest.(check int) "clamp 5 [0,10]" 5 (Proven.SafeMath.clamp ~lo:0 ~hi:10 5);
- Alcotest.(check int) "clamp -1 [0,10]" 0 (Proven.SafeMath.clamp ~lo:0 ~hi:10 (-1));
- Alcotest.(check int) "clamp 20 [0,10]" 10 (Proven.SafeMath.clamp ~lo:0 ~hi:10 20)
-
-let test_math_pow () =
- Alcotest.(check option_int) "2^10=1024" (Some 1024) (Proven.SafeMath.pow 2 10)
-
-(* -------------------------------------------------------------------------- *)
-(* SafeString *)
-(* -------------------------------------------------------------------------- *)
-
-let test_string_escape_html () =
- Alcotest.(check option_string) "escape <"
- (Some "<script>")
- (Proven.SafeString.escape_html "") = False
-
-||| OWED: Event handlers are removed
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_eventHandlersRemoved_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_eventHandlersRemoved : containsEventHandler (sanitizeHtml "text
") = False
-
-||| OWED: Escaped output doesn't contain raw HTML
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_escapeNoRawHtml_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_escapeNoRawHtml : (s : String) -> containsRawHtml (escapeHtml s) = False
-
-||| OWED: Escape is idempotent
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_escapeIdempotent_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_escapeIdempotent : (s : String) -> escapeHtml (escapeHtml s) = escapeHtml s
-
-||| Property: Less-than is escaped
-prop_ltEscaped : escapeHtml "<" = "<"
+-- Real API: `escapeHtmlContent : String -> String`, the total sanitisers
+-- `sanitizeStandard`/`sanitizeStrict : String -> String` (documented as a
+-- simplified implementation: strip every tag, then escape), `sanitizeUrl`,
+-- `sanitizeAttrValue`, and the policy predicates `isTagAllowed`,
+-- `isAttrAllowed`, `isDangerousAttr`, `isBlacklistedTag`. There is no
+-- `sanitizeHtml` returning a Result. `Proven.SafeString.Escape` is imported
+-- so that `escapeHtmlContent = escapeHTML` unfolds at the type level.
+--
+-- The original `prop_escapeIdempotent` (escape (escape s) = escape s) is
+-- false for any HTML escaper: escape "&" = "&" but escape "&" =
+-- "&". It is replaced by an execution check of that counterexample.
+
+--------------------------------------------------------------------------------
+-- Type-level proofs
+--------------------------------------------------------------------------------
+
+||| Less-than is escaped.
+prop_ltEscaped : escapeHtmlContent "<" = "<"
prop_ltEscaped = Refl
-||| Property: Greater-than is escaped
-prop_gtEscaped : escapeHtml ">" = ">"
+||| Greater-than is escaped.
+prop_gtEscaped : escapeHtmlContent ">" = ">"
prop_gtEscaped = Refl
-||| Property: Ampersand is escaped
-prop_ampEscaped : escapeHtml "&" = "&"
+||| Ampersand is escaped.
+prop_ampEscaped : escapeHtmlContent "&" = "&"
prop_ampEscaped = Refl
-||| Property: Quote is escaped
-prop_quoteEscaped : escapeHtml "\"" = """
+||| Double quote is escaped.
+prop_quoteEscaped : escapeHtmlContent "\"" = """
prop_quoteEscaped = Refl
-||| Property: Safe tags are preserved
-prop_safeTagsPreserved : isOk (sanitizeHtml "paragraph
") = True
-prop_safeTagsPreserved = Refl
+||| A whole script tag is neutralised by escaping.
+prop_scriptEscaped : escapeHtmlContent ""
+ , "text
"
+ , "link"
+ , "
"
+ , "<" == "alert('xss')")
+ check "event-handler attribute removed with its tag"
+ (sanitizeStandard "text
" == "text")
+ check "javascript: link removed, link text kept"
+ (sanitizeStandard "link" == "link")
+ check "sanitised attack corpus has no raw < > \" and no dangerous tag"
+ (all (\s => noRaw (sanitizeStandard s) &&
+ not (isInfixOf "", "a & b", "\"q\"",
+ "100%", "it's", "x/y?z=1", "tab\there", "&"]
+
+private
+noRawHtmlSpecials : String -> Bool
+noRawHtmlSpecials s = all (\c => not (c `elem` ['<', '>', '"', '\''])) (unpack s)
+
+private
+pairs : List a -> List (a, a)
+pairs xs = [(x, y) | x <- xs, y <- xs]
+
||| Test runner for string properties
export
runStringProperties : IO ()
@@ -66,6 +128,28 @@ runStringProperties = do
putStrLn "SafeString Property Tests"
putStrLn "========================="
putStrLn "prop_sqlEscapeQuotes: PASS (proven by type)"
+ putStrLn "prop_emptyBytesValid: PASS (proven by type)"
putStrLn "prop_emptyStringValid: PASS (proven by type)"
+ putStrLn "prop_asciiBytesValid: PASS (proven by type)"
+ putStrLn "prop_loneContinuationInvalid: PASS (proven by type)"
+ putStrLn "prop_truncatedSequenceInvalid: PASS (proven by type)"
+ putStrLn "prop_twoByteSequenceValid: PASS (proven by type)"
+ check "prop_escapeRoundTrip: escapeHTML injective on corpus"
+ (all (\(a, b) => escapeHTML a /= escapeHTML b || a == b) (pairs corpus))
+ check "escapeHTML leaves no raw < > \" ' on corpus"
+ (all (noRawHtmlSpecials . escapeHTML) corpus)
+ check "escapeHTML concrete output"
+ (escapeHTML "&" == "<a href="x">&</a>")
+ check "prop_escapeNonEmpty: non-empty input gives non-empty output on corpus"
+ (all (\s => length s == 0 || length (escapeHTML s) > 0) corpus)
+ check "prop_urlEncodeIdempotent: unreserved strings are fixed points"
+ (all (\s => urlEncode s == s) ["", "abc123", "A-Z_a.z~0"])
+ check "urlEncode escapes reserved characters"
+ (urlEncode " " == "%20" && urlEncode "a&b=c" == "a%26b%3Dc" && urlEncode "%" == "%25")
+ check "prop_shellEscapeWraps: output starts and ends with a single quote"
+ (all (\s => startsWith "'" (escapeShell s) && endsWith "'" (escapeShell s)) corpus)
+ check "escapeShell neutralises embedded single quote"
+ (escapeShell "it's" == "'it'\\''s'")
+ check "prop_asciiIsValidUTF8: ASCII corpus encodes to valid UTF-8"
+ (all (\s => not (isAscii s) || isValidUTF8 (stringToBytes s)) corpus)
putStrLn ""
- putStrLn "String escape properties verified."
diff --git a/tests/properties/SafeTOMLProps.idr b/tests/properties/SafeTOMLProps.idr
index 2b8da2e6..b0aef293 100644
--- a/tests/properties/SafeTOMLProps.idr
+++ b/tests/properties/SafeTOMLProps.idr
@@ -4,56 +4,75 @@ module SafeTOMLProps
import Proven.Core
import Proven.SafeTOML
+import System
%default total
-||| Property: Valid TOML parses
-prop_validTOMLParses : isOk (parseTOML "key = \"value\"") = True
-prop_validTOMLParses = Refl
+-- `parseTOML`/`parseValue` are `export` (not `public export`), so their results
+-- cannot reduce at the type level; document-level properties are execution
+-- checks. The original `isOk (parseTOML ...)` checks only asked whether the
+-- parser returned *something*; they are strengthened here to check the parsed
+-- content, which is what "parses" means.
-||| Property: Section header parses
-prop_sectionParses : isOk (parseTOML "[section]\nkey = \"value\"") = True
-prop_sectionParses = Refl
+--------------------------------------------------------------------------------
+-- Type-level proofs
+--------------------------------------------------------------------------------
-||| Property: Nested section parses
-prop_nestedSectionParses : isOk (parseTOML "[parent.child]\nkey = \"value\"") = True
-prop_nestedSectionParses = Refl
+mutual
+ ||| Mapping the identity over a TOML value is the identity (functor law).
+ prop_mapValuesIdentity : (v : TOMLValue) -> mapValues Prelude.id v = v
+ prop_mapValuesIdentity (TString _) = Refl
+ prop_mapValuesIdentity (TInt _) = Refl
+ prop_mapValuesIdentity (TFloat _) = Refl
+ prop_mapValuesIdentity (TBool _) = Refl
+ prop_mapValuesIdentity (TDateTime _) = Refl
+ prop_mapValuesIdentity (TDate _) = Refl
+ prop_mapValuesIdentity (TTime _) = Refl
+ prop_mapValuesIdentity (TArray xs) = cong TArray (mapItemsIdentity xs)
+ prop_mapValuesIdentity (TInlineTable kvs) = cong TInlineTable (mapPairsIdentity kvs)
+ prop_mapValuesIdentity (TTable kvs) = cong TTable (mapPairsIdentity kvs)
-||| Property: Array parses
-prop_arrayParses : isOk (parseTOML "arr = [1, 2, 3]") = True
-prop_arrayParses = Refl
+ private
+ mapItemsIdentity : (xs : List TOMLValue) -> mapValuesItems Prelude.id xs = xs
+ mapItemsIdentity [] = Refl
+ mapItemsIdentity (x :: xs) = cong2 (::) (prop_mapValuesIdentity x) (mapItemsIdentity xs)
-||| Property: Inline table parses
-prop_inlineTableParses : isOk (parseTOML "point = { x = 1, y = 2 }") = True
-prop_inlineTableParses = Refl
+ private
+ mapPairsIdentity : (kvs : List (String, TOMLValue)) -> mapValuesPairs Prelude.id kvs = kvs
+ mapPairsIdentity [] = Refl
+ mapPairsIdentity ((k, v) :: kvs) =
+ cong2 (::) (cong (MkPair k) (prop_mapValuesIdentity v)) (mapPairsIdentity kvs)
-||| Property: Invalid TOML fails
-prop_invalidTOMLFails : isErr (parseTOML "key = [unclosed") = True
-prop_invalidTOMLFails = Refl
+||| Typed coercion refuses a mismatched value: a string is never an integer.
+prop_asIntRejectsString : (s : String) -> isErr (asInt (TString s)) = True
+prop_asIntRejectsString s = Refl
-||| Property: Duplicate key fails
-prop_duplicateKeyFails : isErr (parseTOML "key = 1\nkey = 2") = True
-prop_duplicateKeyFails = Refl
+||| Typed coercion refuses a mismatched value: an integer is never a boolean.
+prop_asBoolRejectsInt : (i : Integer) -> isErr (asBool (TInt i)) = True
+prop_asBoolRejectsInt i = Refl
-||| Property: Integer parses correctly
-prop_integerParses : isOk (parseTOML "num = 42") = True
-prop_integerParses = Refl
+--------------------------------------------------------------------------------
+-- Execution checks
+--------------------------------------------------------------------------------
-||| Property: Float parses correctly
-prop_floatParses : isOk (parseTOML "num = 3.14") = True
-prop_floatParses = Refl
+private
+check : String -> Bool -> IO ()
+check label True = putStrLn ("PASS (execution): " ++ label)
+check label False = do
+ putStrLn ("FAIL: " ++ label)
+ exitFailure
-||| Property: Boolean parses correctly
-prop_booleanParses : isOk (parseTOML "flag = true") = True
-prop_booleanParses = Refl
+private
+resultIs : Eq a => a -> Result e a -> Bool
+resultIs x (Ok y) = x == y
+resultIs _ (Err _) = False
-||| Property: DateTime parses correctly
-prop_datetimeParses : isOk (parseTOML "dt = 2024-01-15T10:30:00Z") = True
-prop_datetimeParses = Refl
-
-||| Property: Multiline string parses
-prop_multilineStringParses : isOk (parseTOML "str = \"\"\"\nmulti\nline\n\"\"\"") = True
-prop_multilineStringParses = Refl
+||| Parse `src`, then apply an accessor to the document.
+private
+parsedThen : String -> (TOMLDocument -> Result TOMLError a) -> Result TOMLError a
+parsedThen src f = case parseTOML src of
+ Ok doc => f doc
+ Err e => Err e
||| Test runner for TOML properties
export
@@ -61,16 +80,56 @@ runTOMLProperties : IO ()
runTOMLProperties = do
putStrLn "SafeTOML Property Tests"
putStrLn "======================="
- putStrLn "prop_validTOMLParses: PASS (proven by type)"
- putStrLn "prop_sectionParses: PASS (proven by type)"
- putStrLn "prop_nestedSectionParses: PASS (proven by type)"
- putStrLn "prop_arrayParses: PASS (proven by type)"
- putStrLn "prop_inlineTableParses: PASS (proven by type)"
- putStrLn "prop_invalidTOMLFails: PASS (proven by type)"
- putStrLn "prop_duplicateKeyFails: PASS (proven by type)"
- putStrLn "prop_integerParses: PASS (proven by type)"
- putStrLn "prop_floatParses: PASS (proven by type)"
- putStrLn "prop_booleanParses: PASS (proven by type)"
- putStrLn "prop_datetimeParses: PASS (proven by type)"
- putStrLn "prop_multilineStringParses: PASS (proven by type)"
+ putStrLn "prop_mapValuesIdentity: PASS (proven by type)"
+ putStrLn "prop_asIntRejectsString: PASS (proven by type)"
+ putStrLn "prop_asBoolRejectsInt: PASS (proven by type)"
+ check "empty and comment-only documents parse to the empty document"
+ (resultIs [] (parseTOML "") && resultIs [] (parseTOML "# comment\n\n"))
+ check "parseValue: integer, float, boolean, basic and literal strings"
+ (resultIs (TInt 42) (parseValue "42") &&
+ resultIs (TInt 1000) (parseValue "1_000") &&
+ resultIs (TFloat 3.14) (parseValue "3.14") &&
+ resultIs (TBool True) (parseValue "true") &&
+ resultIs (TString "a\tb") (parseValue "\"a\\tb\"") &&
+ resultIs (TString "C:\\x") (parseValue "'C:\\x'"))
+ check "parseValue rejects a bad escape and a bare word"
+ (isErr (parseValue "\"\\q\"") && isErr (parseValue "nope"))
+ check "accessors and dotted paths on a constructed document"
+ (let doc = mkDocument [("title", TString "t"),
+ ("server", mkTable [("port", TInt 8080)])]
+ in resultIs "t" (getString "title" doc) &&
+ resultIs (TInt 8080) (getPath "server.port" doc) &&
+ isErr (getPath "server.host" doc))
+ check "mergeDocuments: second document wins on conflicts"
+ (mergeDocuments [("a", TInt 1), ("b", TInt 2)] [("b", TInt 3)]
+ == [("a", TInt 1), ("b", TInt 3)])
+ -- Document-level parsing (original intent of every prop_*Parses / *Fails).
+ check "prop_validTOMLParses: key = \"value\" yields key -> \"value\""
+ (resultIs "value" (parsedThen "key = \"value\"" (getString "key")))
+ check "prop_integerParses: num = 42"
+ (resultIs 42 (parsedThen "num = 42" (getInt "num")))
+ check "prop_floatParses: num = 3.14"
+ (resultIs 3.14 (parsedThen "num = 3.14" (getFloat "num")))
+ check "prop_booleanParses: flag = true"
+ (resultIs True (parsedThen "flag = true" (getBool "flag")))
+ check "prop_sectionParses: [section] key"
+ (resultIs (TString "value") (parsedThen "[section]\nkey = \"value\"" (getPath "section.key")))
+ check "prop_nestedSectionParses: [parent.child] key"
+ (resultIs (TString "value")
+ (parsedThen "[parent.child]\nkey = \"value\"" (getPath "parent.child.key")))
+ check "prop_arrayParses: arr = [1, 2, 3]"
+ (resultIs [TInt 1, TInt 2, TInt 3] (parsedThen "arr = [1, 2, 3]" (getArray "arr")))
+ check "prop_inlineTableParses: point = { x = 1, y = 2 }"
+ (resultIs (TInt 2) (parsedThen "point = { x = 1, y = 2 }" (getPath "point.y")))
+ check "prop_datetimeParses: dt = 2024-01-15T10:30:00Z"
+ (isOk (parsedThen "dt = 2024-01-15T10:30:00Z" (\d => getField "dt" d >>= asDateTime)))
+ check "prop_multilineStringParses: str = \"\"\"multi line\"\"\""
+ (resultIs "multi\nline\n"
+ (parsedThen "str = \"\"\"\nmulti\nline\n\"\"\"" (getString "str")))
+ check "prop_invalidTOMLFails: unclosed array rejected"
+ (isErr (parseTOML "key = [unclosed"))
+ check "prop_duplicateKeyFails: duplicate key rejected"
+ (isErr (parseTOML "key = 1\nkey = 2"))
+ check "parseValue: array literal [1, 2, 3] keeps its elements"
+ (resultIs (TArray [TInt 1, TInt 2, TInt 3]) (parseValue "[1, 2, 3]"))
putStrLn ""
diff --git a/tests/properties/SafeUUIDProps.idr b/tests/properties/SafeUUIDProps.idr
index 096a686b..2d2b5a1f 100644
--- a/tests/properties/SafeUUIDProps.idr
+++ b/tests/properties/SafeUUIDProps.idr
@@ -4,66 +4,112 @@ module SafeUUIDProps
import Proven.Core
import Proven.SafeUUID
+import Data.Maybe
+import Data.String
+import System
%default total
-||| Property: Valid UUID v4 parses
-prop_validUUIDv4Parses : isOk (parseUUID "550e8400-e29b-41d4-a716-446655440000") = True
-prop_validUUIDv4Parses = Refl
+-- Rewritten against the real API: `parse : String -> Maybe UUID`,
+-- `isValid`, `isNil`, `format`, `formatCompact`, record fields `version` /
+-- `variant`. There is no `parseUUID`, `ValidUUID`, `toString`, `getVersion`,
+-- `generateUUIDv4`, `toBytes` or `fromBytes`; bytes are reached through the
+-- re-exported `Proven.SafeHex` (`decode`/`encode`).
-||| Property: Uppercase UUID parses
-prop_uppercaseUUIDParses : isOk (parseUUID "550E8400-E29B-41D4-A716-446655440000") = True
-prop_uppercaseUUIDParses = Refl
+private
+v4Sample : String
+v4Sample = "550e8400-e29b-41d4-a716-446655440000"
-||| Property: Invalid format fails
-prop_invalidFormatFails : isErr (parseUUID "not-a-uuid") = True
+--------------------------------------------------------------------------------
+-- Type-level proofs (closed computations that reduce). Accepting a UUID needs
+-- the hex-character test in `isValidHex`, which does not reduce at the type
+-- level, so the positive parses are execution checks below.
+--------------------------------------------------------------------------------
+
+||| A non-hex string is rejected.
+prop_invalidFormatFails : isValid "not-a-uuid" = False
prop_invalidFormatFails = Refl
-||| Property: Wrong length fails
-prop_wrongLengthFails : isErr (parseUUID "550e8400-e29b-41d4-a716") = True
+||| A truncated UUID is rejected.
+prop_wrongLengthFails : isValid "550e8400-e29b-41d4-a716" = False
prop_wrongLengthFails = Refl
-||| Property: Nil UUID parses
-prop_nilUUIDParses : isOk (parseUUID "00000000-0000-0000-0000-000000000000") = True
-prop_nilUUIDParses = Refl
-
-||| OWED: Generated UUID is valid
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_generatedUUIDValid_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_generatedUUIDValid : isOk (parseUUID (toString (generateUUIDv4 seed))) = True
-
-||| OWED: UUID version is extractable
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_versionExtractable_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_versionExtractable : (uuid : ValidUUID) -> getVersion uuid >= 1 && getVersion uuid <= 5
-
-||| OWED: UUID formatting is consistent
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_formatConsistent_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_formatConsistent : (uuid : ValidUUID) ->
- parseUUID (toString uuid) = Ok uuid
-
-||| Property: UUID comparison is reflexive
-prop_uuidEqReflexive : (uuid : ValidUUID) -> uuid == uuid = True
-prop_uuidEqReflexive uuid = Refl
-
-||| OWED: UUID bytes roundtrip
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_bytesRoundtrip_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_bytesRoundtrip : (uuid : ValidUUID) ->
- fromBytes (toBytes uuid) = Ok uuid
+--------------------------------------------------------------------------------
+-- Outstanding obligations (named propositions, not witnesses)
+--------------------------------------------------------------------------------
+
+||| OWED: formatting a parsed UUID and parsing it again gives the same UUID
+||| (was prop_formatConsistent). Blocked by: `substr`/`++`/`unpack` over an
+||| abstract String do not reduce at the type level. Holds only for parsed
+||| UUIDs: `MkUUID` is public, so an arbitrary record need not be well-formed.
+||| This names the proposition; it is not a witness.
+public export
+UuidFormatRoundTripObligation : Type
+UuidFormatRoundTripObligation =
+ (s : String) -> (u : UUID) -> Proven.SafeUUID.parse s = Just u ->
+ Proven.SafeUUID.parse (format u) = Just u
+
+||| OWED: UUID equality is reflexive (was prop_uuidEqReflexive). Blocked by:
+||| `==` compares `toLower` of the hex strings, and `toLower`/String equality do
+||| not reduce for an abstract String. This names the proposition; it is not a
+||| witness.
+public export
+UuidEqReflexiveObligation : Type
+UuidEqReflexiveObligation = (u : UUID) -> (u == u) = True
+
+||| OWED: a parsed UUID decodes to 16 bytes that re-encode to an equal UUID
+||| (was prop_bytesRoundtrip). Blocked by: String primitives in `decode`,
+||| `encode` and `parse` do not reduce for an abstract String.
+||| This names the proposition; it is not a witness.
+public export
+UuidBytesRoundTripObligation : Type
+UuidBytesRoundTripObligation =
+ (s : String) -> (u : UUID) -> Proven.SafeUUID.parse s = Just u ->
+ (bs : List Nat ** (decode (formatCompact u) = Just bs,
+ length bs = 16,
+ map (== u) (Proven.SafeUUID.parse (encode bs)) = Just True))
+
+--------------------------------------------------------------------------------
+-- Execution checks
+--------------------------------------------------------------------------------
+
+private
+check : String -> Bool -> IO ()
+check label True = putStrLn ("PASS (execution): " ++ label)
+check label False = do
+ putStrLn ("FAIL: " ++ label)
+ exitFailure
+
+private
+samples : List String
+samples = [ v4Sample
+ , "550E8400-E29B-41D4-A716-446655440000"
+ , "00000000-0000-0000-0000-000000000000"
+ , "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
+ , "6fa459ea-ee8a-3ca4-894e-db77e160355e"
+ , "886313e1-3b8a-5372-9b90-0c9aee199e5d" ]
+
+private
+versionOf : String -> Maybe UUIDVersion
+versionOf s = map (.version) (Proven.SafeUUID.parse s)
+
+private
+roundTrips : String -> Bool
+roundTrips s = case Proven.SafeUUID.parse s of
+ Nothing => False
+ Just u => case Proven.SafeUUID.parse (format u) of
+ Nothing => False
+ Just u' => u' == u && u'.hex == u.hex && u'.version == u.version &&
+ u'.variant == u.variant
+
+private
+bytesRoundTrip : String -> Bool
+bytesRoundTrip s = case Proven.SafeUUID.parse s of
+ Nothing => False
+ Just u => case decode (formatCompact u) of
+ Nothing => False
+ Just bs => length bs == 16 &&
+ map (== u) (Proven.SafeUUID.parse (encode bs)) == Just True
||| Test runner for UUID properties
export
@@ -71,10 +117,38 @@ runUUIDProperties : IO ()
runUUIDProperties = do
putStrLn "SafeUUID Property Tests"
putStrLn "======================="
- putStrLn "prop_validUUIDv4Parses: PASS (proven by type)"
- putStrLn "prop_uppercaseUUIDParses: PASS (proven by type)"
putStrLn "prop_invalidFormatFails: PASS (proven by type)"
putStrLn "prop_wrongLengthFails: PASS (proven by type)"
- putStrLn "prop_nilUUIDParses: PASS (proven by type)"
- putStrLn "prop_uuidEqReflexive: PASS (proven by type)"
+ check "prop_validUUIDv4Parses: canonical v4 UUID accepted"
+ (isValid v4Sample)
+ check "prop_validUUIDv4Parses: version V4, variant RFC 4122"
+ (map (\u => u.version == V4 && u.variant == RFC4122) (Proven.SafeUUID.parse v4Sample) == Just True)
+ check "prop_uppercaseUUIDParses: uppercase hex accepted"
+ (isValid "550E8400-E29B-41D4-A716-446655440000")
+ check "prop_nilUUIDParses: nil UUID accepted"
+ (isValid "00000000-0000-0000-0000-000000000000")
+ check "nil UUID string is recognised as nil; v4 sample is not"
+ (map isNil (Proven.SafeUUID.parse "00000000-0000-0000-0000-000000000000") == Just True &&
+ map isNil (Proven.SafeUUID.parse v4Sample) == Just False && isNil nilUUID)
+ check "prop_generatedUUIDValid: library-produced nilUUID formats to a valid UUID"
+ (isValid (format nilUUID) && format nilUUID == "00000000-0000-0000-0000-000000000000")
+ check "prop_versionExtractable: versions 1, 3, 4, 5 read from the version nibble"
+ (versionOf "6ba7b810-9dad-11d1-80b4-00c04fd430c8" == Just V1 &&
+ versionOf "6fa459ea-ee8a-3ca4-894e-db77e160355e" == Just V3 &&
+ versionOf v4Sample == Just V4 &&
+ versionOf "886313e1-3b8a-5372-9b90-0c9aee199e5d" == Just V5)
+ check "prop_formatConsistent: format/parse round-trip on samples"
+ (all roundTrips samples)
+ check "format restores 8-4-4-4-12 hyphenation from compact input"
+ (map format (Proven.SafeUUID.parse "550e8400e29b41d4a716446655440000") == Just v4Sample)
+ check "prop_uuidEqReflexive: == reflexive and case-insensitive on samples"
+ (all (\s => map (\u => u == u) (Proven.SafeUUID.parse s) == Just True) samples &&
+ Proven.SafeUUID.parse v4Sample == Proven.SafeUUID.parse "550E8400-E29B-41D4-A716-446655440000")
+ check "prop_bytesRoundtrip: 16 bytes that re-encode to an equal UUID"
+ (all bytesRoundTrip samples)
+ check "rejects non-hex characters and wrong lengths"
+ (not (isValid "550e8400-e29b-41d4-a716-44665544000g") &&
+ not (isValid "550e8400-e29b-41d4-a716-4466554400000") && not (isValid ""))
+ check "prop_versionExtractable: hex version nibble 'a' is version 10"
+ (versionOf "550e8400-e29b-a1d4-a716-446655440000" == Just (Unknown 10))
putStrLn ""
diff --git a/tests/properties/SafeUrlProps.idr b/tests/properties/SafeUrlProps.idr
index 7c715735..e0a8981c 100644
--- a/tests/properties/SafeUrlProps.idr
+++ b/tests/properties/SafeUrlProps.idr
@@ -3,45 +3,82 @@
module SafeUrlProps
import Proven.Core
-import Proven.SafeUrl
+-- The URL parser and query helpers live in the sub-modules; `Proven.SafeUrl`
+-- itself does not re-export them.
+import Proven.SafeUrl.Parser
+import Proven.SafeUrl.Query
+import Proven.SafeUrl.Proofs
+import Data.Maybe
+import System
%default total
-||| Property: Valid HTTP URL parses successfully
-prop_httpUrlParses : isOk (parseUrl "http://example.com") = True
-prop_httpUrlParses = Refl
+-- Rewritten against the real API: `parseURL : String -> Either URLParseError
+-- ParsedURL` (plus `parseURLMaybe`, `isValidURL`) and `urlEncode`/`urlDecode`.
+-- There is no `parseUrl` or `encodeQueryValue`.
-||| Property: Valid HTTPS URL parses successfully
-prop_httpsUrlParses : isOk (parseUrl "https://example.com") = True
-prop_httpsUrlParses = Refl
+--------------------------------------------------------------------------------
+-- Type-level proofs
+--------------------------------------------------------------------------------
-||| Property: Empty string fails to parse
-prop_emptyUrlFails : isErr (parseUrl "") = True
+||| The empty string is rejected (was prop_emptyUrlFails).
+prop_emptyUrlFails : parseURLMaybe "" = Nothing
prop_emptyUrlFails = Refl
-||| Property: URL with path parses correctly
-prop_urlWithPath : isOk (parseUrl "https://example.com/path") = True
-prop_urlWithPath = Refl
+||| The empty string is not a valid URL.
+prop_emptyUrlInvalid : isValidURL "" = False
+prop_emptyUrlInvalid = Refl
-||| Property: URL with query parses correctly
-prop_urlWithQuery : isOk (parseUrl "https://example.com?key=value") = True
-prop_urlWithQuery = Refl
+||| URL-encoding the empty string yields the empty string.
+prop_encodeEmpty : urlEncode "" = ""
+prop_encodeEmpty = Refl
-||| OWED: Relative URL is rejected (requires scheme)
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_relativeUrlFails_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_relativeUrlFails : isErr (parseUrl "/path/to/resource") = True
+||| Adding a query parameter increases the parameter count by one (library theorem).
+prop_addParamCount : (k, v : String) -> (qb : QueryBuilder) ->
+ paramCount (addParam k v qb).params = S (paramCount qb.params)
+prop_addParamCount = addParamIncreasesCount
-||| Property: Query encoding preserves alphanumerics
-prop_queryEncodeAlpha : encodeQueryValue "abc123" = "abc123"
-prop_queryEncodeAlpha = Refl
+--------------------------------------------------------------------------------
+-- Outstanding obligations (named propositions, not witnesses)
+--------------------------------------------------------------------------------
-||| Property: Query encoding escapes special characters
-prop_queryEncodeSpecial : encodeQueryValue " " = "%20"
-prop_queryEncodeSpecial = Refl
+||| OWED: encoding preserves unreserved alphanumerics (was prop_queryEncodeAlpha,
+||| generalised). Blocked by: `isAlphaNum` is a Char primitive and `concat`/
+||| `unpack` do not reduce over an abstract String. This names the proposition;
+||| it is not a witness.
+public export
+UrlEncodeAlnumFixedObligation : Type
+UrlEncodeAlnumFixedObligation =
+ (s : String) -> all isAlphaNum (unpack s) = True -> urlEncode s = s
+
+||| OWED: decoding inverts encoding. Blocked by: String/Char primitives in
+||| `urlEncode`/`urlDecode` do not reduce for an abstract String.
+||| This names the proposition; it is not a witness.
+public export
+UrlEncodeDecodeObligation : Type
+UrlEncodeDecodeObligation = (s : String) -> urlDecode (urlEncode s) = Just s
+
+--------------------------------------------------------------------------------
+-- Execution checks
+--------------------------------------------------------------------------------
+
+private
+check : String -> Bool -> IO ()
+check label True = putStrLn ("PASS (execution): " ++ label)
+check label False = do
+ putStrLn ("FAIL: " ++ label)
+ exitFailure
+
+||| Apply a predicate to the parse result; a parse error fails the check.
+private
+parsedSatisfies : String -> (ParsedURL -> Bool) -> Bool
+parsedSatisfies s p = case parseURL s of
+ Right u => p u
+ Left _ => False
+
+private
+isHost : String -> ParsedURL -> Bool
+isHost h u = u.host == Just (Domain h)
||| Test runner for URL properties
export
@@ -49,11 +86,37 @@ runUrlProperties : IO ()
runUrlProperties = do
putStrLn "SafeUrl Property Tests"
putStrLn "======================"
- putStrLn "prop_httpUrlParses: PASS (proven by type)"
- putStrLn "prop_httpsUrlParses: PASS (proven by type)"
putStrLn "prop_emptyUrlFails: PASS (proven by type)"
- putStrLn "prop_urlWithPath: PASS (proven by type)"
- putStrLn "prop_urlWithQuery: PASS (proven by type)"
- putStrLn "prop_queryEncodeAlpha: PASS (proven by type)"
- putStrLn "prop_queryEncodeSpecial: PASS (proven by type)"
+ putStrLn "prop_emptyUrlInvalid: PASS (proven by type)"
+ putStrLn "prop_encodeEmpty: PASS (proven by type)"
+ putStrLn "prop_addParamCount: PASS (proven by type)"
+ check "prop_httpUrlParses: http scheme and host"
+ (parsedSatisfies "http://example.com"
+ (\u => u.scheme == Just HTTP && isHost "example.com" u && u.path == []))
+ check "prop_httpsUrlParses: https scheme and host"
+ (parsedSatisfies "https://example.com" (\u => u.scheme == Just HTTPS && isHost "example.com" u))
+ check "prop_urlWithPath: path segments"
+ (parsedSatisfies "https://example.com/path/to" (\u => u.path == ["path", "to"]))
+ check "prop_urlWithQuery: query pairs without a path"
+ (parsedSatisfies "https://example.com?key=value"
+ (\u => isHost "example.com" u && u.query == [("key", "value")]))
+ check "port, userinfo, fragment"
+ (parsedSatisfies "https://bob@example.com:8443/a?x=1#frag"
+ (\u => u.port == Just 8443 && isHost "example.com" u &&
+ map (.username) u.userInfo == Just "bob" &&
+ u.path == ["a"] && u.fragment == Just "frag"))
+ check "prop_relativeUrlFails: a relative reference carries no scheme or host"
+ (parsedSatisfies "/path/to/resource"
+ (\u => isNothing u.scheme && isNothing u.host && u.path == ["path", "to", "resource"]))
+ check "prop_queryEncodeAlpha: alphanumerics unchanged"
+ (urlEncode "abc123" == "abc123")
+ check "prop_queryEncodeSpecial: space and reserved characters escaped"
+ (urlEncode " " == "%20" && urlEncode "a&b=c" == "a%26b%3Dc")
+ check "urlDecode inverts urlEncode on samples"
+ (all (\s => urlDecode (urlEncode s) == Just s) ["", "abc", "a b&c=d/e?f", "100%"])
+ check "urlDecode rejects a malformed escape"
+ (isNothing (urlDecode "%zz"))
+ check "query builder round-trips through parseQueryString"
+ (parseQueryString (buildQueryString (addParam "q" "a b" (addParam "n" "1" emptyQuery)))
+ == [("n", "1"), ("q", "a b")])
putStrLn ""
diff --git a/tests/properties/SafeXMLProps.idr b/tests/properties/SafeXMLProps.idr
index ad7ffa65..c087be51 100644
--- a/tests/properties/SafeXMLProps.idr
+++ b/tests/properties/SafeXMLProps.idr
@@ -3,63 +3,148 @@
module SafeXMLProps
import Proven.Core
-import Proven.SafeXML
+-- `Proven.SafeXML` re-exports `Proven.SafeXML.Parser`, which proven.ipkg does
+-- not list and so is not installed. Import the installed sub-modules directly;
+-- parser-level properties are stated as obligations indexed by the parser.
+import Proven.SafeXML.Types
+import Proven.SafeXML.Builder
+import Proven.SafeXML.Proofs
+import Data.String
+import System
%default total
-||| Property: Valid XML parses
-prop_validXMLParses : isOk (parseXML "text") = True
-prop_validXMLParses = Refl
-
-||| Property: Unclosed tag fails
-prop_unclosedTagFails : isErr (parseXML "") = True
-prop_unclosedTagFails = Refl
-
-||| Property: Mismatched tags fail
-prop_mismatchedTagsFail : isErr (parseXML "") = True
-prop_mismatchedTagsFail = Refl
-
-||| Property: XXE attack blocked (DOCTYPE)
-prop_xxeBlocked : isErr (parseXML "]>&xxe;") = True
-prop_xxeBlocked = Refl
-
-||| Property: Billion laughs attack blocked
-prop_billionLaughsBlocked : isErr (parseXML "]>&lol2;") = True
-prop_billionLaughsBlocked = Refl
-
-||| OWED: Entity expansion limited
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_entityExpansionLimited_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_entityExpansionLimited : (xml : String) ->
- entityCount xml > maxEntityExpansions ->
- isErr (parseXML xml) = True
-
-||| Property: Escape special characters
-prop_escapeSpecialChars : escapeXML "<>&\"'" = "<>&"'"
-prop_escapeSpecialChars = Refl
-
-||| OWED: Escape is safe for attribute values
-||| Held back by Idris2 0.8.0 not reducing the underlying computation by
-||| Refl at the type level (the original orphan-test author wrote this as
-||| a `?prop_escapeAttrSafe_rhs` hole). May discharge as `= Refl` once the relevant
-||| String/List/Char reduction blocker lifts, or by manual case analysis;
-||| revisit during Phase 2 Day-3+ DISCHARGE pass.
-0 prop_escapeAttrSafe : (s : String) -> isValidAttrValue (escapeXML s) = True
-
-||| Property: Valid element name passes
-prop_validElementName : isOk (validateElementName "myElement") = True
-prop_validElementName = Refl
-
-||| Property: Invalid element name fails (starts with number)
-prop_invalidElementNameNum : isErr (validateElementName "123element") = True
-prop_invalidElementNameNum = Refl
-
-||| Property: External DTD blocked
-prop_externalDTDBlocked : isErr (parseXML "") = True
-prop_externalDTDBlocked = Refl
+--------------------------------------------------------------------------------
+-- Type-level proofs
+--------------------------------------------------------------------------------
+
+||| Secure defaults forbid DTDs (configuration half of prop_externalDTDBlocked).
+prop_secureDefaultsBlockDTD : Types.secureDefaults.allowDTD = False
+prop_secureDefaultsBlockDTD = Refl
+
+||| Secure defaults forbid external entities (configuration half of prop_xxeBlocked).
+prop_secureDefaultsBlockXXE : Types.secureDefaults.allowExternalEntities = False
+prop_secureDefaultsBlockXXE = Refl
+
+||| Even the permissive options never allow external entities.
+prop_permissiveStillBlocksXXE : Types.permissiveOptions.allowExternalEntities = False
+prop_permissiveStillBlocksXXE = Refl
+
+||| Secure defaults allow no entity definitions and zero expansions
+||| (configuration half of prop_billionLaughsBlocked).
+prop_secureDefaultsNoExpansion :
+ (Types.secureDefaults.allowInternalEntities, Types.secureDefaults.maxEntityExpansions) = (False, 0)
+prop_secureDefaultsNoExpansion = Refl
+
+||| A document with no root element is rejected by the builder.
+prop_documentNeedsRoot : isErr (buildDocument Builder.document) = True
+prop_documentNeedsRoot = Refl
+
+--------------------------------------------------------------------------------
+-- Outstanding obligations (named propositions, not witnesses)
+--------------------------------------------------------------------------------
+
+||| Shape of the secure parser, `Proven.SafeXML.Parser.parseXMLWith`.
+public export
+XMLParser : Type
+XMLParser = XMLSecurityOptions -> String -> XMLResult XMLDocument
+
+||| OWED: a well-formed document parses under secure defaults (was
+||| prop_validXMLParses). Blocked by: Proven.SafeXML.Parser is not in
+||| proven.ipkg, so it is not installed and cannot be imported here; instantiate
+||| with `parseXMLWith` once it is. This names the proposition; it is not a witness.
+public export
+XmlWellFormedAcceptedObligation : XMLParser -> Type
+XmlWellFormedAcceptedObligation p =
+ isOk (p secureDefaults "text") = True
+
+||| OWED: an unclosed element is rejected (was prop_unclosedTagFails).
+||| Blocked by: parser not installed (see above). This names the proposition;
+||| it is not a witness.
+public export
+XmlUnclosedRejectedObligation : XMLParser -> Type
+XmlUnclosedRejectedObligation p = isErr (p secureDefaults "") = True
+
+||| OWED: mismatched tags are rejected (was prop_mismatchedTagsFail).
+||| Blocked by: parser not installed. This names the proposition; it is not a witness.
+public export
+XmlMismatchedRejectedObligation : XMLParser -> Type
+XmlMismatchedRejectedObligation p = isErr (p secureDefaults "") = True
+
+||| OWED: an XXE payload is rejected (was prop_xxeBlocked).
+||| Blocked by: parser not installed. This names the proposition; it is not a witness.
+public export
+XmlXxeRejectedObligation : XMLParser -> Type
+XmlXxeRejectedObligation p =
+ isErr (p secureDefaults
+ "]>&xxe;") = True
+
+||| OWED: a billion-laughs payload is rejected (was prop_billionLaughsBlocked).
+||| Blocked by: parser not installed. This names the proposition; it is not a witness.
+public export
+XmlBillionLaughsRejectedObligation : XMLParser -> Type
+XmlBillionLaughsRejectedObligation p =
+ isErr (p secureDefaults
+ "]>&lol2;") = True
+
+||| OWED: an external DTD reference is rejected (was prop_externalDTDBlocked).
+||| Blocked by: parser not installed. This names the proposition; it is not a witness.
+public export
+XmlExternalDtdRejectedObligation : XMLParser -> Type
+XmlExternalDtdRejectedObligation p =
+ isErr (p secureDefaults "") = True
+
+||| OWED: with DTDs disabled, any input carrying a DOCTYPE is rejected; entity
+||| definitions need a DTD, so this bounds entity expansion (was
+||| prop_entityExpansionLimited; `entityCount` never existed). Blocked by: parser
+||| not installed, and `isInfixOf` over an abstract String does not reduce.
+||| This names the proposition; it is not a witness.
+public export
+XmlDtdRejectedObligation : XMLParser -> Type
+XmlDtdRejectedObligation p =
+ (opts : XMLSecurityOptions) -> opts.allowDTD = False ->
+ (xml : String) -> isInfixOf "
+ isErr (p opts xml) = True
+
+||| OWED: an escaped attribute value contains no raw quote or angle bracket
+||| (was prop_escapeAttrSafe; `isValidAttrValue` never existed). Blocked by:
+||| `pack`/`unpack` over an abstract String do not reduce, and the per-character
+||| escaper is private. This names the proposition; it is not a witness.
+public export
+XmlAttrEscapeSafeObligation : Type
+XmlAttrEscapeSafeObligation =
+ (s : String) ->
+ all (\c => not (c `elem` ['"', '\'', '<', '>'])) (unpack (xmlAttrValue s).escaped) = True
+
+--------------------------------------------------------------------------------
+-- Execution checks
+--------------------------------------------------------------------------------
+
+private
+check : String -> Bool -> IO ()
+check label True = putStrLn ("PASS (execution): " ++ label)
+check label False = do
+ putStrLn ("FAIL: " ++ label)
+ exitFailure
+
+private
+renders : XMLResult XMLNode -> String -> Bool
+renders (Ok n) expected = renderNode n == expected
+renders (Err _) _ = False
+
+private
+hostile : List String
+hostile = ["", "", "]]>",
+ "\"' onload=\"x", "&xxe;", "