# ARKHEIA public SDK quickstart

The API origin is `https://arkheia-cps-10.onrender.com`. These Python and TypeScript SDKs use public endpoints and out-of-band public key pins only. They contain no signing credentials, issue no leases, and never substitute the separate legacy `/v1` key family.

**Offline clearance signature verification is available.** The user-supplied [wire specification v1.0.1](./wire-spec-v1.0.1.md) defines Ed25519, lowercase hex signatures, integers-only RFC 8785 JCS, and domain-separated signing bytes. The supplied document is 122 lines and ends during OBSERVATION; HUMAN_RELEASE's field set was separately supplied by the user. It does **not** supply an exact closed clearance-receipt schema, response envelope/extraction path, or execution-authorization fields. A verifier returning `True`/`true` authenticates the signed bytes only. It is not schema validation, freshness validation, an execution permit, or permission to execute an action.

The public [MANDATE fixture](./fixtures/mandate.json) and its CUSTOS lease signatures both verify **offline**. They are not a clearance receipt or an accepted live POST demonstration. **Do not POST or replay that `payments.transfer` fixture.** No new live POST was made while implementing these SDKs.

## Pin the engine key

The configured clearance key is:

- ID: `ed25519:a2008a603a195230`
- Raw Ed25519 public key hex: `9e2c04f0027bce2844eb10241a9b107d215d0dfa384c537acf45d75d4f97aa27`

A read-only head check compares **both** fields:

```bash
curl --fail-with-body --max-time 20 \
  https://arkheia-cps-10.onrender.com/api/clearance/head
```

A matching head is not receipt authentication. Missing or changed pins block transport; never adopt a head key as automatic key rotation. Require an authenticated out-of-band operator instruction to change configured pins. Offline verification uses only the configured raw key; a receipt-provided key is never a trust root. If a receipt contains `public_key_id`, it must equal the configured ID, and that field remains part of the signed object.

## Python: install cryptography

Use Python 3.10+ and copy `sdk/arkheia.py` into your project. From this repository:

```bash
python3 -m pip install -r sdk/requirements.txt
python3 sdk/arkheia.py head --timeout 20
```

Offline verification, with no network request:

```python
from sdk.arkheia import load_json_file, verify_clearance_receipt

# Obtain the actual standalone clearance receipt from the operator.
# Do not guess which field of a gate response contains it.
receipt = load_json_file("clearance-receipt.json")
signature_valid = verify_clearance_receipt(receipt)
print({"signature_valid": signature_valid, "execution_authorized": False})
if not signature_valid:
    raise SystemExit("BLOCKED: invalid or malformed receipt")
# Even here, do NOT execute a protected action. A closed receipt schema,
# authorization/permit contract and contextual checks have not been supplied.
```

The new verification and public-byte helper signatures are:

```python
verify_clearance_receipt(receipt: Any) -> bool
canonicalize(value: Any) -> bytes
signing_input(domain: str, artifact: dict[str, Any], signature_field: str = "sig") -> bytes
```

`canonicalize` and `signing_input` raise `InputError` for malformed wire values. `verify_clearance_receipt` returns `False` for invalid/malformed objects, bad signatures, a wrong key ID, or verification errors; it does not raise `UnsupportedReceiptFormat`. That legacy exception name is retained for import compatibility only.

The CLI's `verify` operation is offline:

```bash
python3 sdk/arkheia.py verify ./clearance-receipt.json
```

Exit 0 means **signature valid only** for `verify`, or pins match for `head`; it never means execution authorized. Exit 3 means a structurally parseable receipt did not verify, or a POST transport succeeded but its response remains unverified. Exit 2 means a file/parse, transport, pin, or HTTP error. The CLI always labels receipt verification separately from execution authority.

### Explicit, authorized gate transport

Use newly operator-issued signed requests and obtain explicit authorization before making a POST. Do not use the public fixture as a request. These library methods send only public gate requests; they return raw unverified JSON and do not perform a protected action:

```python
from sdk.arkheia import ArkheiaClient, HTTPError, load_json_file

client = ArkheiaClient(timeout=20)
try:
    # Run only after authorizing this audit-mutating POST.
    raw_response = client.mandate_verify(load_json_file("mandate-request.json"))
    # For a separately authorized Aegis request:
    # raw_response = client.aegis_evaluate(load_json_file("aegis-request.json"))
    print("Transport completed; response is unverified")
except HTTPError as error:
    print("Gate rejected or HTTP failure:", error.status)
    # error.response_json preserves structured errors. Avoid sensitive body logs.
    raise SystemExit(1)
```

CLI equivalents are `python3 sdk/arkheia.py mandate ./mandate-request.json --timeout 20` and `python3 sdk/arkheia.py aegis ./aegis-request.json --timeout 20`. They are not read-only demonstrations.

## TypeScript: asynchronous WebCrypto Ed25519

Copy `sdk/arkheia.ts` into your project. No runtime package dependencies are required. Use **Node 20+ recommended**, or a modern secure-context browser with WebCrypto Ed25519. Node 18 has `fetch` but global `crypto`/Ed25519 availability depends on its version and launch mode; where supported, enable `--experimental-global-webcrypto`, or explicitly supply Node's `webcrypto` as `globalThis.crypto` in your application bootstrap. The SDK itself has no Node-only import or alternate verification fallback. Missing or unsupported WebCrypto returns `false`; fail closed.

An offline Node example using your existing TypeScript runner/compilation setup:

```typescript
import { readFile } from "node:fs/promises";
import { parseJsonObject, verifyClearanceReceipt } from "./sdk/arkheia";

async function main() {
  const receipt = parseJsonObject(await readFile("clearance-receipt.json", "utf8"));
  const signatureValid = await verifyClearanceReceipt(receipt); // MUST await
  console.log({ signature_valid: signatureValid, execution_authorized: false });
  if (!signatureValid) throw new Error("BLOCKED: invalid or malformed receipt");
  // Signature authenticity is not an execution permit. Do not execute here.
}
void main().catch(error => {
  console.error(error instanceof Error ? error.message : "Verification failed");
  process.exitCode = 1;
});
```

New method signatures:

```typescript
verifyClearanceReceipt(receipt: unknown): Promise<boolean>
canonicalize(value: unknown): Uint8Array
signingInput(domain: string, artifact: JsonObject, signatureField = "sig"): Uint8Array
```

`ArkheiaClient.clearanceHead(): Promise<JsonObject>` checks both pins. After separately authorizing a POST, `mandateVerify(payload: JsonObject): Promise<JsonObject>` or `aegisEvaluate(payload: JsonObject): Promise<JsonObject>` transports the operator-issued request; the returned JSON remains unverified. Both call the read-only head pin check before POST. The exported `CLEARANCE_KEY_PIN` is out-of-band configuration, not a dynamic trust store; only tests temporarily substitute generated public pins.

Browser file input can use `parseJsonObject(await selectedFile.text())`. To parse **raw bytes** without silent UTF-8 replacement or BOM stripping, use `new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(await selectedFile.arrayBuffer())`, then the strict parser. Browser HTTP access still depends on the service's CORS policy, which was not established. Do not expose lease-bearing payloads, credentials, or personal data in frontend analytics or example URLs.

## Exact signature preimage and input profile

For a clearance receipt, both SDKs verify:

```text
ASCII("ARKHEIA/clearance/receipt/v1") || 0x00 ||
JCS(the entire received object with only top-level "signature" removed)
```

`signature` must be exactly 128 **lowercase** hex characters (64 Ed25519 bytes). All other fields remain signed, including nested signatures, hashes, unknown fields and a present `public_key_id`. No receipt fields are guessed, inserted, normalized, or silently discarded. Execution permits use a **different** domain, `ARKHEIA/mandate/permit/v1`; a permit signature is not valid as a clearance-receipt signature.

The strict reader rejects duplicate keys (including escape-equivalent names), any decimal/exponent numeric token (`1.0`, `1e0`), non-finite values, unsafe integers outside `±(2^53−1)`, BOM, invalid UTF-8, lone surrogates, and nesting depth over 64. JCS emits UTF-8, minimal JSON string escaping, plain decimal integers, no whitespace, and UTF-16 code-unit key order. It neither normalizes Unicode nor coerces strings to numbers. Use the strict parser on original text: an ordinary JSON parser has already erased duplicate keys and numeric-token spellings. JavaScript object numbers cannot distinguish `1` from `1.0` after parsing; fractional/unsafe numbers are still rejected by object validation.

Requests are capped at **65,536 bytes**, matching the supplied wire limit. Responses and canonicalized objects also use that cap as SDK safety policy. Transport emits JCS, rejects redirects, and never retries POSTs. Python's timeout applies per blocking operation; TypeScript's abort deadline covers the request and response body. A timeout may leave an audit outcome unknown.

## Supplied request contracts and remaining boundaries

All supplied artifact object schemas are closed with every key required; the SDK's generic transport/parser is **not** a closed schema validator. See [API contract notes](./api-contract-notes.md) for the exact CUSTOS, A2A, MANDATE, OBSERVATION and HUMAN_RELEASE field sets, primitive types, issuer checks, signature domains and excerpt limitations.

CUSTOS lease wire format and issuer checks are now supplied and implemented by the provisioning backend. Configure its approved grant policy and Stripe price, and enroll the actual issuer in the engine's operator-controlled trust file before accepting purchases. A valid fixture signature alone does not prove live trust, freshness, replay clearance or permit issuance. See [provisioning instructions](./provisioning.md).

Historical validation probes appended audit rejections to the live chain; these SDK changes performed **no live POSTs**. Empty-object POSTs are opaque rejections, not free read-only demos. Never infer approval from HTTP 200, a hash, a matching head, or even a valid receipt signature without the missing authorization contract.

## Offline SDK tests

```bash
python3 -m unittest discover -s sdk/tests -p 'test_*.py' -v
pnpm exec vitest run --config sdk/tests/vitest.config.ts
```

Transport is mocked. Receipt tests generate ephemeral Ed25519 keys and patch only public pin values, with no static private keys. Positive/negative coverage includes wrong domains/keys, tampering, malformed signatures, optional key IDs, UTF-16 sorting, strict wire parsing and limits. Both suites verify the supplied public fixture signatures offline using the known issuer. No project package or configuration edits are required for copying these standalone SDKs.
