# Kokum ABI 1.12: binary, cryptographic and persistent transport services

This is an approved extension of the official Kokum compiler and VM. It adds
37 public builtins, numbered 125–161. Existing builtins 1–124 retain their
identifiers, names, argument counts and result types. The native runtime ABI
remains 1.2, the GUI ABI remains 1.10, and bytecode/KAPP formats remain 1.3.
Existing application bundles are not rewritten by installing the runtime.

The compiler records the minimum ABI required by each resolved operation.
Code using the new operations requires VM ABI 1.12. Code using only older
features keeps its previous minimum. User functions, procedures, lexical
callables and imported functions that share a new builtin name retain their
binding. An older VM rejects a new-feature bundle before executing it.

## Capability map

| Area | Public APIs | Detailed contract |
|---|---|---|
| Binary files | BINOPEN, BINREAD, BINWRITE, BINSEEK, BINTELL, BINSIZE, BINFLUSH, BINCLOSE, BINREPLACE | `docs/binary_io_v1.md` |
| Streaming digest | SHA256BEGIN, SHA256UPDATE, SHA256FINAL, SHA256CLOSE | `docs/binary_io_v1.md` |
| Keys and cryptography | CRYPTOKEYGEN, CRYPTOKEYIMPORT, CRYPTOPUBLICKEY, CRYPTOKEYCLOSE, CRYPTOAEADSEAL, CRYPTOAEADOPEN, CRYPTOSIGN, CRYPTOVERIFY, CRYPTOX25519, CRYPTOHKDF, CRYPTOHPKESEAL, CRYPTOHPKEOPEN, CRYPTOKEYSAVE, CRYPTOKEYLOAD | `docs/crypto_v2.md` |
| Persistent WebSocket transport | WSSERVER, WSNEXT, WSAUTHORIZE, WSREJECT, WSSEND, WSSENDTEXT, WSCLOSE, WSREVOKE, WSINFO, WSFLOWCONTROL | `docs/websocket_server_v1.md` |

Binary values use existing ARRAYs of strict INTEGER octets from 0 to 255.
Kokum array indexing remains one-based. File and crypto calls impose documented
input bounds; they do not require loading an entire video into a STRING.
ARRAY element and allocator overhead is additional to raw byte counts.
Existing text OPEN/READ/WRITE behavior is preserved.

## One KAPP with HTTP workers and a persistent service owner

The native backend accepts these optional `[server]` settings:

```ini
[server]
listen=127.0.0.1
port=8787
workers=4
queue_capacity=32
startup_handler=HttpWorkerStartup
service_startup_handler=RelayStartup
service_tick_handler=RelayTick
service_shutdown_handler=RelayShutdown
service_tick_ms=25
```

The ordinary HTTP startup handler still runs in each HTTP worker. When
`service_tick_handler` is present, the host also creates exactly one persistent
service VM on a dedicated thread. Its optional startup callback, repeated tick
callback and optional shutdown callback all run on that thread. Resources
created in startup can remain in that service VM's PUBLIC variables and be
used by later ticks and shutdown. They must not be passed to an HTTP worker.

The service VM and HTTP worker VMs have separate globals. They can each use
the existing declared database component; the host initializes that component
in every session. Application metadata and notifications can be coordinated
through the application database. The runtime does not invent shared globals
or serialize file, key or WebSocket handles between VMs.

All service callbacks take no arguments and return INTEGER 0 on success.
Startup and shutdown settings require a tick handler. The tick interval ranges
from 1 through 1000 milliseconds; its default is 25. The interval is a wait
between callbacks, not a wall-clock execution deadline. All callback names are
resolved before service startup runs. If startup partly fails, the resolved
shutdown callback still has an opportunity to clean up, and VM-owned resource
finalizers run on the owner thread.

A startup, tick or shutdown failure is reported as KBE1513 with a fixed host
message. A failed tick stops the host instead of leaving an apparently healthy
HTTP service with a dead background relay. Existing HTTP callback behavior is
preserved when the new settings are absent.

Shutdown is cooperative. Keep each tick bounded: consume a limited number of
events, use zero or short WSNEXT waits, and use bounded database/network calls.
The existing HTTP `graceful_shutdown_ms` does not forcibly interrupt arbitrary
Kokum code or an indefinitely blocked native call.

## Event handling and authentication

Declare the event variable without `AS MAP`, because WSNEXT returns either a
MAP or NULL. For example, inside a bounded application callback:

```kokum
LOCAL event
event=WSNEXT(relay,0)
IF event=NULL
 RETURN 0
ENDIF
```

A `request` event arrives before HTTP 101. Application code validates the
credential against its account/session policy and calls WSAUTHORIZE with a
stable member identity and the validated absolute Unix-millisecond expiry.
The event timestamp uses the same time unit. Do not turn a claimed email or
client-supplied identity into an authenticated identity. WSREJECT returns a
bounded native JSON HTTP rejection. Payload frames are not accepted before
authorization succeeds.

Catch expected peer-disconnect and queue-pressure errors around authorization
and sends. KSV6005 indicates an unavailable/stale connection; KSV6007 indicates
budget pressure. An uncaught application error fails the service tick. A
successful send means queue acceptance, not peer receipt or durable storage.
Applications still need transfer IDs, sequence numbers, authenticated framing,
acknowledgments, retries and duplicate handling.

Expiry and revocation stop further authorized transport operations. An event
queued while a session was valid is a historical snapshot. Recheck current
recipient, friendship, post visibility and moderation policy before forwarding
it. Transport authorization does not implement those application policies.

## TLS routing boundary

WSSERVER binds IPv4 loopback only. Place it behind the existing trusted HTTPS
reverse proxy, with an explicit WebSocket route and HTTP/1.1 Upgrade forwarding.
The HTTP account service and WebSocket listener can use separate local ports
while appearing under one public hostname. Preserve the established
authentication boundary for unrelated gateway paths.

The source acceptance test `tests/abi112/test_service_websocket.py` builds one
portable KAPP, starts both listeners, tests unauthorized and authorized upgrade
paths, then repeats binary/text/revocation checks through a real Nginx TLS
proxy when `--nginx` is supplied. It verifies the test CA and hostname and
separately checks that an untrusted certificate is rejected. It also confirms
that the account route remains reachable and rejects unauthorized upgrades
with native JSON rather than a gateway HTML response.

These are disposable fixtures. They do not modify the live infinetus.com
gateway, its certificate, DNS, accounts or application bundles.

## Key and content responsibilities

The application crypto APIs use the OpenSSL provider. The fixed HPKE suite is
RFC 9180 X25519/HKDF-SHA256/AES-256-GCM in Base or Auth mode. Ed25519 signs
authenticated application metadata; AES-GCM authenticates a bounded chunk and
its associated metadata. Public test vectors and an independent implementation
are included in the source tests.

AES-GCM nonce uniqueness is the application's responsibility. Allocate a
fresh content key for each object and define a tested chunk/nonce schedule.
Opaque private handles are not serializable. The tested
`tests/abi112_crypto/hex_key_example.kokum` recipe decodes existing SECURERANDOM
hex into random content-key bytes, imports the AES key and HPKE-wraps those
bytes. The decoding step is serialization, not a custom cryptographic primitive.

CRYPTOKEYSAVE stores a protected encrypted key file. Use a separate vault
unlock/recovery policy; a server login token is not automatically a content
decryption key. Native handle cleanup cleans owned secret buffers, while
caller-created ARRAYs and STRINGs retain the existing ordinary-memory behavior.
The vault is portable file protection, not an OS hardware-keystore guarantee.

The relay implementation has no payload database, disk spool or content log.
That property concerns this runtime component. Application code, reverse-proxy
logging, swap, crash dumps and host snapshots have separate deployment policies.
An offline peer cannot receive an in-memory-only transfer; the future social
application must make retry/availability behavior explicit.

## Building and verification

On Linux, use the existing supported development dependencies and `make` or
the CMake build. The ordinary Make OpenSSL path still uses shared SDK linkage;
the earlier static-link correction is retained. Windows keeps its existing
strict C99 format checks and MinGW stdio compatibility fix. macOS keeps its
native publisher, permission preparation, library relocation and signing flow.

`make abi112-test` executes binary/API/vector, language, loader, portable,
service lifecycle and WebSocket wire checks. The independent crypto oracle
also runs with:

```bash
python3 tests/abi112_crypto/test_interoperability.py --native-api build/abi112/crypto_api
```

That oracle needs the Python cryptography test dependency. Application users
do not need Python. `tests/abi112/test_portable.py --kokumvm /path/kokumvm`
runs frozen KBC/KAPP fixtures without a compiler and is used by release
packagers to refuse old binaries relabeled as ABI 1.12.

The new source guard records the 199 common runtime files, all unchanged
historical ledgers and the complete source inventory. Exact previous versions
of changed files are retained under `phases/abi112/predecessor/`. The read-only
guard can verify the release or restore the exact corrected ABI 1.11 source
to a new external directory. Integrity checks establish file identity;
execution results and platform limitations are reported separately.

The existing source license remains authoritative. This upgrade does not
change Kokum's proprietary licensing.
