Part VI · Complete Annotated Examples & Showcase Applications
Appendix C.2
Complete Examples Catalog: Protocols, Vaults, Stdlib & PQC (Examples 13–22)
Unabridged listings covering pure-Veko TLS 1.3, HTTP APIs, encrypted vaults, query dialects, NIST PQC, and WebSockets
Complete unabridged source listings for Examples 13 through 22, covering pure-Veko TLS 1.3, concurrent HTTP microservices, encrypted vaults, query dialects, standard library foundations, NIST PQC, HTTP/2, and WebSockets.
Example 13: 13_pure_vk_tls13_and_codecs.vk
Run command: veko -A examples/13_pure_vk_tls13_and_codecs.vk
Example 13: Pure-Veko DER/PEM/HTTP Codecs, X.509 PEM & SPKI Pinning & Loopback TLS 1.3 (M9) Zero OS crypto DLLs: runs 100% pure .vk across ORO VM, .vko, Wasm 3, and --native. Track A (.vko) : veko compile --vko examples/13_pure_vk_tls13_and_codecs.vk -o dist/13.vko ; veko run --allow-net --allow-listen --allow-private-net dist/13.vko Track C (Native) : veko compile --native examples/13_pure_vk_tls13_and_codecs.vk -o dist/13.exe ; ./dist/13.exe
1 │ // Example 13: Pure-Veko DER/PEM/HTTP Codecs, X.509 PEM & SPKI Pinning & Loopback TLS 1.3 (M9)
2 │ // Zero OS crypto DLLs: runs 100% pure .vk across ORO VM, .vko, Wasm 3, and --native.
3 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/13_pure_vk_tls13_and_codecs.vk
4 │ // Track A (.vko) : veko compile --vko examples/13_pure_vk_tls13_and_codecs.vk -o dist/13.vko ; veko run --allow-net --allow-listen --allow-private-net dist/13.vko
5 │ // Track B (Wasm 3) : veko run --wasm --fuel=0 --allow-net --allow-listen --allow-private-net examples/13_pure_vk_tls13_and_codecs.vk
6 │ // Track C (Native) : veko compile --native examples/13_pure_vk_tls13_and_codecs.vk -o dist/13.exe ; ./dist/13.exe
7 │
8 │ use [
9 │ der = codec/der,
10 │ pem = codec/pem,
11 │ http = codec/http1,
12 │ sha = crypto/sha256,
13 │ kx = crypto/x25519,
14 │ x509 = crypto/x509,
15 │ tls13 = net/tls13
16 │ ]
17 │
18 │ // 1. ASN.1 DER encoding + homoiconic `parse-block` inspection
19 │ s1 = der/encode-seq [(der/encode-int (der/from-list [42])) (der/encode-tlv 0x06 (der/from-list [0x2b 0x65 0x70]))]
20 │ blk1 = der/tlv-to-block (der/decode-tlv s1 0)
21 │ mut got_inner = []
22 │ mut got_oid = []
23 │ mut got_int = []
24 │ _ = parse-block blk1 [ any [ [.seq inner = block!] [ push mut got_inner inner ] ] ]
25 │ _ = parse-block got_inner[0] [
26 │ any [
27 │ [.int ib = any! .oid oid = str!] [
28 │ push mut got_int ib
29 │ push mut got_oid oid
30 │ ]
31 │ ]
32 │ ]
33 │ println (str/join ['der=' (mold got_int[0][0]) '|' got_oid[0]] '')
34 │
35 │ // 2. RFC 8032 Ed25519 + X.509 PEM root & SPKI certificate pinning
36 │ ca_seed = sha/sha256 (bytes/from-str 'veko-example-root-ca')
37 │ leaf_seed = sha/sha256 (bytes/from-str 'veko-example-leaf')
38 │ ca_der = x509/mint-ed25519-cert {
39 │ issuer_cn = 'Veko Example Root', subject_cn = 'Veko Example Root', is_ca = true,
40 │ subject_seed = ca_seed, signer_seed = ca_seed, serial = 1
41 │ }
42 │ leaf_der = x509/mint-ed25519-cert {
43 │ issuer_cn = 'Veko Example Root', subject_cn = 'svc.veko.local', is_ca = false,
44 │ san_dns = ['svc.veko.local'], san_ips = ['127.0.0.1'],
45 │ subject_seed = leaf_seed, signer_seed = ca_seed, serial = 2
46 │ }
47 │ roots_pem = pem/pem-encode 'CERTIFICATE' ca_der
48 │ leaf_info = x509/parse-cert leaf_der
49 │ println (str/join ['cert=' leaf_info.subject_cn '|pin=' leaf_info.spki_hex[0..16]] '')
50 │
51 │ // 3. Live loopback RFC 8446 TLS 1.3 + HTTP/1.1 exchange over pure-Veko sockets
52 │ ln = net/listen-tcp .ip '127.0.0.1:0'
53 │ port = str/to-i64 (str/split (net/addr ln) ':')[1]
54 │
55 │ srv = spawn [
56 │ sock = net/accept ln
57 │ mut sconn = tls13/server-handshake sock [leaf_der ca_der] leaf_seed
58 │ req = http/decode-request (tls13/recv mut sconn)
59 │ body = bytes/from-str (str/join ['tls13-ok:' req.method ':' req.target] '')
60 │ _w = tls13/send mut sconn (http/encode-response 200 'OK' { Content-Type = 'text/plain' } body)
61 │ tls13/close mut sconn
62 │ 'done'
63 │ ]
64 │
65 │ resp = tls13/https-request '127.0.0.1' port 'GET' '/health' {} (bytes/with-cap 0) {
66 │ server_name = 'svc.veko.local'
67 │ roots_pem = roots_pem
68 │ pins_sha256 = [leaf_info.spki_hex]
69 │ }
70 │ _ = task/await srv
71 │ net/close ln
72 │ println (str/join ['https=' (mold resp.status) '|' (bytes/to-str resp.body)] '')Example 14: 14_http_json_api_server.vk
Run command: veko -A examples/14_http_json_api_server.vk
Example 14: Multi-Worker Concurrent HTTP/1.1 + JSON REST Microservice Demonstrates codec/http1, net/*, shared-nothing spawn actor + worker pool, reusable per-worker channels, typed struct + struct/with, parse-block, and .secret firewall. Track A (.vko) : veko compile --vko examples/14_http_json_api_server.vk -o dist/14.vko ; veko run --allow-net --allow-listen --allow-private-net dist/14.vko Track C (Native) : veko compile --native examples/14_http_json_api_server.vk -o dist/14.exe ; ./dist/14.exe
1 │ // Example 14: Multi-Worker Concurrent HTTP/1.1 + JSON REST Microservice
2 │ // Demonstrates `codec/http1`, `net/*`, shared-nothing `spawn` actor + worker pool,
3 │ // reusable per-worker channels, typed `struct` + `struct/with`, `parse-block`, and `.secret` firewall.
4 │ //
5 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
6 │ // Track A (.vko) : veko compile --vko examples/14_http_json_api_server.vk -o dist/14.vko ; veko run --allow-net --allow-listen --allow-private-net dist/14.vko
7 │ // Track B (Wasm 3) : veko run --wasm --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
8 │ // Track C (Native) : veko compile --native examples/14_http_json_api_server.vk -o dist/14.exe ; ./dist/14.exe
9 │
10 │ use [http = codec/http1, json, bytes, net, str, time]
11 │
12 │ TaskItem = struct {
13 │ id i64
14 │ title str
15 │ priority i64 = 1
16 │ done bool = false
17 │ }
18 │
19 │ ApiMetrics = struct {
20 │ handled i64
21 │ created i64
22 │ workers i64
23 │ }
24 │
25 │ parse-port = fn [addr str] i64 [
26 │ parts = str/split addr ':'
27 │ str/to-i64/or parts[1] [0]
28 │ ]
29 │
30 │ is-json-map? = fn [v any] bool [
31 │ (type-of v) == .map_val
32 │ ]
33 │
34 │ is-json-str? = fn [v any] bool [
35 │ t = type-of v
36 │ t == .str or t == .str_inline or t == .str_heap
37 │ ]
38 │
39 │ is-json-num? = fn [v any] bool [
40 │ t = type-of v
41 │ t == .i64_val or t == .f64_val
42 │ ]
43 │
44 │ // Loop `net/read-bytes/or` until full HTTP/1.1 headers + Content-Length body arrive
45 │ read-http-request = fn [sock any] any [
46 │ mut buf = bytes/with-cap 0
47 │ forever [
48 │ chunk = net/read-bytes/or sock 4096 [bytes/with-cap 0]
49 │ if (len chunk) == 0 [
50 │ return (err 'http: unexpected EOF reading request')
51 │ ]
52 │ bytes/push-all (mut buf) chunk
53 │ dec = http/decode-request buf
54 │ if ok? dec [
55 │ return dec
56 │ ]
57 │ ]
58 │ err 'http: unreachable'
59 │ ]
60 │
61 │ read-http-response = fn [sock any] any [
62 │ mut buf = bytes/with-cap 0
63 │ forever [
64 │ chunk = net/read-bytes/or sock 4096 [bytes/with-cap 0]
65 │ if (len chunk) == 0 [
66 │ return (err 'http: unexpected EOF reading response')
67 │ ]
68 │ bytes/push-all (mut buf) chunk
69 │ dec = http/decode-response buf
70 │ if ok? dec [
71 │ return dec
72 │ ]
73 │ ]
74 │ err 'http: unreachable'
75 │ ]
76 │
77 │ // Parse `/items/<id>` (need_done=false) or `/items/<id>/done` (need_done=true)
78 │ parse-item-id = fn [target str, need_done bool] i64 [
79 │ parts = str/split target '/'
80 │ if need_done [
81 │ if (len parts) == 4 and parts[1] == 'items' and parts[3] == 'done' [
82 │ return (str/to-i64/or parts[2] [-1])
83 │ ]
84 │ return -1
85 │ ]
86 │ if (len parts) == 3 and parts[1] == 'items' [
87 │ return (str/to-i64/or parts[2] [-1])
88 │ ]
89 │ -1
90 │ ]
91 │
92 │ // Dedicated store actor owns mutable REST state inside its isolated task heap
93 │ run-store-actor = fn [store_ch any, worker_count i64] i64 [
94 │ mut items = []
95 │ mut next_id = 1
96 │ mut handled = 0
97 │ mut created = 0
98 │
99 │ forever [
100 │ cmd = chan/recv/or store_ch [break]
101 │ op = cmd.op
102 │ handled = handled + 1
103 │
104 │ resp = match op [
105 │ 'health' [
106 │ { status = 200, reason = 'OK', body = { status = 'ok', service = 'veko-api' } }
107 │ ]
108 │ 'create' [
109 │ item = TaskItem {
110 │ id = next_id
111 │ title = cmd.title
112 │ priority = cmd.priority
113 │ done = false
114 │ }
115 │ push mut items item
116 │ next_id = next_id + 1
117 │ created = created + 1
118 │ { status = 201, reason = 'Created', body = item }
119 │ ]
120 │ 'list' [
121 │ { status = 200, reason = 'OK', body = { count = (len items), items = items } }
122 │ ]
123 │ 'get' [
124 │ mut found = .none
125 │ mut i = 0
126 │ while i < (len items) [
127 │ it = items[i]
128 │ if it.id == cmd.id [
129 │ found = it
130 │ ]
131 │ i = i + 1
132 │ ]
133 │ if found == .none [
134 │ { status = 404, reason = 'Not Found', body = { error = 'not_found', id = cmd.id } }
135 │ ] else [
136 │ { status = 200, reason = 'OK', body = found }
137 │ ]
138 │ ]
139 │ 'done' [
140 │ mut updated = .none
141 │ mut next_items = []
142 │ mut i = 0
143 │ while i < (len items) [
144 │ it = items[i]
145 │ if it.id == cmd.id [
146 │ u = it \ struct/with { done = true }
147 │ updated = u
148 │ push mut next_items u
149 │ ] else [
150 │ push mut next_items it
151 │ ]
152 │ i = i + 1
153 │ ]
154 │ items = next_items
155 │ if updated == .none [
156 │ { status = 404, reason = 'Not Found', body = { error = 'not_found', id = cmd.id } }
157 │ ] else [
158 │ { status = 200, reason = 'OK', body = updated }
159 │ ]
160 │ ]
161 │ 'metrics' [
162 │ m = ApiMetrics { handled = handled, created = created, workers = worker_count }
163 │ { status = 200, reason = 'OK', body = m }
164 │ ]
165 │ 'bad_request' [
166 │ { status = 400, reason = 'Bad Request', body = { error = 'invalid_json' } }
167 │ ]
168 │ _ [
169 │ { status = 404, reason = 'Not Found', body = { error = 'not_found' } }
170 │ ]
171 │ ]
172 │ chan/send cmd.reply resp
173 │ ]
174 │ handled
175 │ ]
176 │
177 │ // Worker pool loop: reuses one `reply_ch` per worker across all handled connections
178 │ worker-loop = fn [work_ch any, store_ch any] i64 [
179 │ reply_ch = chan/new 1
180 │ mut served = 0
181 │
182 │ forever [
183 │ conn = chan/recv/or work_ch [break]
184 │ req = read-http-request conn
185 │ if ok? req [
186 │ method = req.method
187 │ target = req.target
188 │ req_body = req.body
189 │
190 │ mut cmd = { op = 'not_found', reply = reply_ch }
191 │ if method == 'GET' and target == '/health' [
192 │ cmd = { op = 'health', reply = reply_ch }
193 │ ] else [
194 │ if method == 'GET' and target == '/items' [
195 │ cmd = { op = 'list', reply = reply_ch }
196 │ ] else [
197 │ if method == 'GET' and target == '/metrics' [
198 │ cmd = { op = 'metrics', reply = reply_ch }
199 │ ] else [
200 │ if method == 'POST' and target == '/items' [
201 │ body_str = bytes/to-str req_body
202 │ dec = json/decode/or body_str [.none]
203 │ if err? dec or dec == .none or not (is-json-map? dec) [
204 │ cmd = { op = 'bad_request', reply = reply_ch }
205 │ ] else [
206 │ raw_title = map/get/or dec 'title' [.none]
207 │ if not (is-json-str? raw_title) [
208 │ cmd = { op = 'bad_request', reply = reply_ch }
209 │ ] else [
210 │ raw_prio = map/get/or dec 'priority' [.none]
211 │ if raw_prio != .none and raw_prio != .null and not (is-json-num? raw_prio) [
212 │ cmd = { op = 'bad_request', reply = reply_ch }
213 │ ] else [
214 │ prio = if raw_prio == .none or raw_prio == .null [ 1 ] else [ as-i64 raw_prio ]
215 │ cmd = { op = 'create', title = raw_title, priority = prio, reply = reply_ch }
216 │ ]
217 │ ]
218 │ ]
219 │ ] else [
220 │ if method == 'POST' [
221 │ done_id = parse-item-id target true
222 │ if done_id > 0 [
223 │ cmd = { op = 'done', id = done_id, reply = reply_ch }
224 │ ]
225 │ ] else [
226 │ if method == 'GET' [
227 │ get_id = parse-item-id target false
228 │ if get_id > 0 [
229 │ cmd = { op = 'get', id = get_id, reply = reply_ch }
230 │ ]
231 │ ]
232 │ ]
233 │ ]
234 │ ]
235 │ ]
236 │ ]
237 │
238 │ chan/send store_ch cmd
239 │ res = chan/recv reply_ch
240 │ json_out = json/encode/or res.body ['{"error":"encode"}']
241 │ hdrs = { Content-Type = 'application/json', Connection = 'close' }
242 │ wire = http/encode-response res.status res.reason hdrs (bytes/from-str json_out)
243 │ _ = net/write/or conn wire [0]
244 │ served = served + 1
245 │ ]
246 │ net/close conn
247 │ ]
248 │
249 │ chan/close reply_ch
250 │ served
251 │ ]
252 │
253 │ accept-loop = fn [ln any, work_ch any, total_reqs i64] i64 [
254 │ mut accepted = 0
255 │ while accepted < total_reqs [
256 │ conn = net/accept ln
257 │ chan/send work_ch conn
258 │ accepted = accepted + 1
259 │ ]
260 │ chan/close work_ch
261 │ accepted
262 │ ]
263 │
264 │ http-call = fn [host str, port i64, method str, target str, body_str str] any [
265 │ cli = net/connect-tcp host port
266 │ hdrs = { Host = '127.0.0.1', Content-Type = 'application/json', Connection = 'close' }
267 │ wire = http/encode-request method target hdrs (bytes/from-str body_str)
268 │ _ = net/write cli wire
269 │ resp = read-http-response cli
270 │ net/close cli
271 │ resp
272 │ ]
273 │
274 │ // 1. Secret governance firewall check & homoiconic `http/request-to-block` + `parse-block` audit
275 │ mut admin_tok = bytes/with-secret 16b
276 │ bytes/push-all (mut admin_tok) (bytes/from-str 'vk-admin-secret')
277 │ sec_box = [admin_tok]
278 │ sec_verdict = json/encode/or { token = sec_box[0] } ['secret-json-blocked']
279 │
280 │ sample_req_wire = http/encode-request 'POST' '/items' { Host = '127.0.0.1', Content-Type = 'application/json' } (bytes/from-str '{"title":"probe"}')
281 │ sample_req = http/decode-request sample_req_wire
282 │ mut parsed_method = ''
283 │ mut parsed_target = ''
284 │ req_blk_ok = parse-block (http/request-to-block sample_req) [
285 │ any [
286 │ [.req m = str! t = str! _v = str! _h = map! _b = any!] [
287 │ parsed_method = m
288 │ parsed_target = t
289 │ ]
290 │ ]
291 │ ]
292 │
293 │ // 2. Bind ephemeral loopback HTTP/1.1 listener and launch store actor + 2 workers
294 │ ln = net/listen-tcp .ip '127.0.0.1:0'
295 │ port = parse-port (net/addr ln)
296 │
297 │ store_ch = chan/new 16
298 │ work_ch = chan/new 16
299 │
300 │ store_task = spawn [run-store-actor store_ch 2]
301 │ w1 = spawn [worker-loop work_ch store_ch]
302 │ w2 = spawn [worker-loop work_ch store_ch]
303 │ acceptor = spawn [accept-loop ln work_ch 8]
304 │
305 │ // 3. Exercise REST API over real loopback TCP HTTP/1.1 connections
306 │ t0 = time/now
307 │
308 │ r_health = http-call '127.0.0.1' port 'GET' '/health' ''
309 │ d_health = json/decode/or (bytes/to-str r_health.body) [{}]
310 │
311 │ r_c1 = http-call '127.0.0.1' port 'POST' '/items' '{"title":"compile-native","priority":3}'
312 │ d_c1 = json/decode/or (bytes/to-str r_c1.body) [{}]
313 │ c1_id = as-i64 (json/get d_c1 'id')
314 │
315 │ r_c2 = http-call '127.0.0.1' port 'POST' '/items' '{"title":"audit-wasm","priority":2}'
316 │ d_c2 = json/decode/or (bytes/to-str r_c2.body) [{}]
317 │ c2_id = as-i64 (json/get d_c2 'id')
318 │
319 │ r_bad = http-call '127.0.0.1' port 'POST' '/items' '{malformed-json'
320 │ d_bad = json/decode/or (bytes/to-str r_bad.body) [{}]
321 │
322 │ r_list = http-call '127.0.0.1' port 'GET' '/items' ''
323 │ d_list = json/decode/or (bytes/to-str r_list.body) [{}]
324 │ list_count = as-i64 (json/get d_list 'count')
325 │
326 │ r_done = http-call '127.0.0.1' port 'POST' '/items/1/done' ''
327 │ d_done = json/decode/or (bytes/to-str r_done.body) [{}]
328 │
329 │ r_miss = http-call '127.0.0.1' port 'GET' '/items/99' ''
330 │ d_miss = json/decode/or (bytes/to-str r_miss.body) [{}]
331 │
332 │ r_met = http-call '127.0.0.1' port 'GET' '/metrics' ''
333 │ d_met = json/decode/or (bytes/to-str r_met.body) [{}]
334 │ met_handled = as-i64 (json/get d_met 'handled')
335 │ met_created = as-i64 (json/get d_met 'created')
336 │ met_workers = as-i64 (json/get d_met 'workers')
337 │
338 │ elapsed = time/since t0
339 │ timing_ok = elapsed >= 0ns
340 │
341 │ // 4. Clean deterministic shutdown
342 │ accepted_total = task/await acceptor
343 │ served_total = (task/await w1) + (task/await w2)
344 │ chan/close store_ch
345 │ actor_handled = task/await store_task
346 │ net/close ln
347 │
348 │ println (str/join ['secret-firewall=' sec_verdict] '')
349 │ println (str/join ['req-block-parsed=' (mold req_blk_ok) ':' parsed_method ':' parsed_target] '')
350 │ println (str/join ['health=' (mold r_health.status) ':' (mold (json/get d_health 'status'))] '')
351 │ println (str/join ['created-ids=' (mold c1_id) ',' (mold c2_id) '|statuses=' (mold r_c1.status) ',' (mold r_c2.status)] '')
352 │ println (str/join ['malformed-json=' (mold r_bad.status) ':' (mold (json/get d_bad 'error'))] '')
353 │ println (str/join ['list-count=' (mold list_count)] '')
354 │ println (str/join ['done-item1=' (mold r_done.status) ':done=' (mold (json/get d_done 'done'))] '')
355 │ println (str/join ['missing-item=' (mold r_miss.status) ':' (mold (json/get d_miss 'error'))] '')
356 │ println (str/join ['metrics=handled:' (mold met_handled) ',created:' (mold met_created) ',workers:' (mold met_workers)] '')
357 │ println (str/join ['pool=accepted:' (mold accepted_total) ',served:' (mold served_total) ',actor:' (mold actor_handled) ',timing-ok=' (mold timing_ok)] '')Example 15: 15_encrypted_vault_cli.vk
Run command: veko -A examples/15_encrypted_vault_cli.vk
Example 15: Authenticated Encrypted File Vault & Ed25519-Signed PEM Manifest CLI Zero OS crypto DLLs: pure-Veko HKDF-SHA256, ChaCha20-Poly1305 AEAD, HMAC-SHA256, Ed25519 manifest signatures, and multi-block PEM storage across ORO VM, Wasm 3, and Native. Self-demo (no args): Track A (.vko) : veko compile --vko examples/15_encrypted_vault_cli.vk -o dist/15.vko ; veko run dist/15.vko Track C (Native) : veko compile --native examples/15_encrypted_vault_cli.vk -o dist/15.exe ; ./dist/15.exe CLI subcommands: veko run examples/15_encrypted_vault_cli.vk -- init <vault.pem> [--pass <pw>] veko run examples/15_encrypted_vault_cli.vk -- set <vault.pem> <key> <value> [--pass <pw>] veko run examples/15_encrypted_vault_cli.vk -- get <vault.pem> <key> [--pass <pw>] veko run examples/15_encrypted_vault_cli.vk -- list <vault.pem> [--pass <pw>] veko run examples/15_encrypted_vault_cli.vk -- verify <vault.pem> veko run --wasm --allow-fs --fuel=0 examples/15_encrypted_vault_cli.vk -- init vault.pem --pass mypw
1 │ // Example 15: Authenticated Encrypted File Vault & Ed25519-Signed PEM Manifest CLI
2 │ // Zero OS crypto DLLs: pure-Veko HKDF-SHA256, ChaCha20-Poly1305 AEAD, HMAC-SHA256,
3 │ // Ed25519 manifest signatures, and multi-block PEM storage across ORO VM, Wasm 3, and Native.
4 │ //
5 │ // Self-demo (no args):
6 │ // Track A (ORO VM) : veko run examples/15_encrypted_vault_cli.vk
7 │ // Track A (.vko) : veko compile --vko examples/15_encrypted_vault_cli.vk -o dist/15.vko ; veko run dist/15.vko
8 │ // Track B (Wasm 3) : veko run --wasm --fuel=0 examples/15_encrypted_vault_cli.vk
9 │ // Track C (Native) : veko compile --native examples/15_encrypted_vault_cli.vk -o dist/15.exe ; ./dist/15.exe
10 │ //
11 │ // CLI subcommands:
12 │ // veko run examples/15_encrypted_vault_cli.vk -- init <vault.pem> [--pass <pw>]
13 │ // veko run examples/15_encrypted_vault_cli.vk -- set <vault.pem> <key> <value> [--pass <pw>]
14 │ // veko run examples/15_encrypted_vault_cli.vk -- get <vault.pem> <key> [--pass <pw>]
15 │ // veko run examples/15_encrypted_vault_cli.vk -- list <vault.pem> [--pass <pw>]
16 │ // veko run examples/15_encrypted_vault_cli.vk -- verify <vault.pem>
17 │ // veko run --wasm --allow-fs --fuel=0 examples/15_encrypted_vault_cli.vk -- init vault.pem --pass mypw
18 │
19 │ use [pem = codec/pem, sha = crypto/sha256, aead = crypto/chacha20, kx = crypto/x25519, json, bytes, str]
20 │
21 │ VaultHeader = struct {
22 │ version i64 = 1
23 │ cipher str = 'chacha20-poly1305'
24 │ kdf str = 'hkdf-sha256'
25 │ pubkey_hex str
26 │ salt_hex str
27 │ nonce_hex str
28 │ mac_hex str
29 │ entries i64
30 │ }
31 │
32 │ VaultSecret = struct {
33 │ name str
34 │ value secret str
35 │ }
36 │
37 │ hex-nibble = fn [b i64] i64 [
38 │ if b >= 48 and b <= 57 [ return (b - 48) ]
39 │ if b >= 97 and b <= 102 [ return (b - 87) ]
40 │ if b >= 65 and b <= 70 [ return (b - 55) ]
41 │ -1
42 │ ]
43 │
44 │ is-map? = fn [v any] bool [
45 │ (type-of v) == .map_val
46 │ ]
47 │
48 │ is-str? = fn [v any] bool [
49 │ t = type-of v
50 │ t == .str or t == .str_inline or t == .str_heap
51 │ ]
52 │
53 │ is-num? = fn [v any] bool [
54 │ t = type-of v
55 │ t == .i64_val or t == .f64_val
56 │ ]
57 │
58 │ hex-to-bytes = fn [hx str] any [
59 │ bs = bytes/from-str hx
60 │ n = len bs
61 │ if (n & 1) != 0 [ return (err 'hex: odd length') ]
62 │ mut out = bytes/with-cap (n >> 1)
63 │ mut i = 0
64 │ while i < n [
65 │ hi = hex-nibble bs[i]
66 │ lo = hex-nibble bs[i + 1]
67 │ if hi < 0 or lo < 0 [ return (err 'hex: invalid hex char') ]
68 │ bytes/push (mut out) ((hi << 4) | lo)
69 │ i = i + 2
70 │ ]
71 │ out
72 │ ]
73 │
74 │ derive-keys = fn [pass str, salt bytes] map [
75 │ prk = sha/hkdf-extract salt (bytes/from-str pass)
76 │ {
77 │ enc_key = sha/hkdf-expand prk (bytes/from-str 'veko-vault-aead-v1') 32
78 │ mac_key = sha/hkdf-expand prk (bytes/from-str 'veko-vault-hmac-v1') 32
79 │ sign_seed = sha/hkdf-expand prk (bytes/from-str 'veko-vault-ed25519-v1') 32
80 │ }
81 │ ]
82 │
83 │ build-aad = fn [ver i64, cipher str, kdf str, pk_hex str, salt_hex str, nonce_hex str, count i64] bytes [
84 │ bytes/from-str (str/join [(mold ver) cipher kdf pk_hex salt_hex nonce_hex (mold count)] '|')
85 │ ]
86 │
87 │ compute-manifest-digest = fn [aad bytes, ct_and_tag bytes] bytes [
88 │ mut buf = bytes/with-cap ((len aad) + (len ct_and_tag))
89 │ bytes/push-all (mut buf) aad
90 │ bytes/push-all (mut buf) ct_and_tag
91 │ sha/sha256 buf
92 │ ]
93 │
94 │ flip-first-byte = fn [src bytes] bytes [
95 │ n = len src
96 │ mut copy = bytes/with-cap n
97 │ if n > 0 [
98 │ bytes/push (mut copy) ((src[0] ^ 0x01) & 0xff)
99 │ if n > 1 [
100 │ bytes/push-all (mut copy) src[1..n]
101 │ ]
102 │ ]
103 │ copy
104 │ ]
105 │
106 │ seal-vault = fn [pass str, salt bytes, nonce bytes, entries map, cached_pk any] any [
107 │ keys = derive-keys pass salt
108 │ pk = if cached_pk == .none [ kx/ed25519-pubkey keys.sign_seed ] else [ cached_pk ]
109 │ if err? pk [ return pk ]
110 │
111 │ pk_hex = sha/to-hex pk
112 │ salt_hex = sha/to-hex salt
113 │ nonce_hex = sha/to-hex nonce
114 │ count = len (map/keys entries)
115 │ aad = build-aad 1 'chacha20-poly1305' 'hkdf-sha256' pk_hex salt_hex nonce_hex count
116 │
117 │ payload_json = json/encode { entries = entries }
118 │ ct_and_tag = aead/aead-encrypt keys.enc_key nonce aad (bytes/from-str payload_json)
119 │ manifest_msg = compute-manifest-digest aad ct_and_tag
120 │ mac_hex = sha/to-hex (sha/hmac-sha256 keys.mac_key manifest_msg)
121 │ sig = kx/ed25519-sign keys.sign_seed manifest_msg
122 │ if err? sig [ return sig ]
123 │
124 │ hdr = VaultHeader {
125 │ version = 1
126 │ cipher = 'chacha20-poly1305'
127 │ kdf = 'hkdf-sha256'
128 │ pubkey_hex = pk_hex
129 │ salt_hex = salt_hex
130 │ nonce_hex = nonce_hex
131 │ mac_hex = mac_hex
132 │ entries = count
133 │ }
134 │ hdr_bytes = bytes/from-str (json/encode hdr)
135 │ pem_text = str/join [
136 │ (pem/pem-encode 'VEKO VAULT HEADER' hdr_bytes)
137 │ (pem/pem-encode 'VEKO VAULT CIPHERTEXT' ct_and_tag)
138 │ (pem/pem-encode 'VEKO VAULT SIGNATURE' sig)
139 │ ] '\n'
140 │
141 │ {
142 │ pem_text = pem_text
143 │ header = hdr
144 │ aad = aad
145 │ ct_and_tag = ct_and_tag
146 │ sig = sig
147 │ pk = pk
148 │ manifest_msg = manifest_msg
149 │ }
150 │ ]
151 │
152 │ parse-vault-pem = fn [pem_text str] any [
153 │ pblk = pem/pem-to-block pem_text
154 │ if err? pblk [ return pblk ]
155 │
156 │ mut hdr_bytes = bytes/with-cap 0
157 │ mut ct_bytes = bytes/with-cap 0
158 │ mut sig_bytes = bytes/with-cap 0
159 │ mut got_hdr = false
160 │ mut got_ct = false
161 │ mut got_sig = false
162 │
163 │ _ = parse-block pblk [
164 │ any [
165 │ [.pem lbl = str! der = any!] [
166 │ if lbl == 'VEKO VAULT HEADER' [
167 │ hdr_bytes = der
168 │ got_hdr = true
169 │ ]
170 │ if lbl == 'VEKO VAULT CIPHERTEXT' [
171 │ ct_bytes = der
172 │ got_ct = true
173 │ ]
174 │ if lbl == 'VEKO VAULT SIGNATURE' [
175 │ sig_bytes = der
176 │ got_sig = true
177 │ ]
178 │ ]
179 │ ]
180 │ ]
181 │
182 │ if not (got_hdr and got_ct and got_sig) [
183 │ return (err 'vault: missing required PEM sections')
184 │ ]
185 │
186 │ hdr_dec = json/decode/or (bytes/to-str hdr_bytes) [.none]
187 │ if err? hdr_dec or hdr_dec == .none or not (is-map? hdr_dec) [
188 │ return (err 'vault: malformed header JSON')
189 │ ]
190 │
191 │ raw_ver = json/get hdr_dec 'version'
192 │ cipher = json/get hdr_dec 'cipher'
193 │ kdf = json/get hdr_dec 'kdf'
194 │ pk_hex = json/get hdr_dec 'pubkey_hex'
195 │ salt_hex = json/get hdr_dec 'salt_hex'
196 │ nonce_hex = json/get hdr_dec 'nonce_hex'
197 │ mac_hex = json/get hdr_dec 'mac_hex'
198 │ raw_entries = json/get hdr_dec 'entries'
199 │
200 │ if not (is-num? raw_ver) or not (is-num? raw_entries) [
201 │ return (err 'vault: malformed header JSON')
202 │ ]
203 │ if not (is-str? cipher) or not (is-str? kdf) [
204 │ return (err 'vault: malformed header JSON')
205 │ ]
206 │ if not (is-str? pk_hex) or (len pk_hex) != 64 [
207 │ return (err 'vault: malformed header JSON')
208 │ ]
209 │ if not (is-str? salt_hex) or (len salt_hex) != 32 [
210 │ return (err 'vault: malformed header JSON')
211 │ ]
212 │ if not (is-str? nonce_hex) or (len nonce_hex) != 24 [
213 │ return (err 'vault: malformed header JSON')
214 │ ]
215 │ if not (is-str? mac_hex) or (len mac_hex) != 64 [
216 │ return (err 'vault: malformed header JSON')
217 │ ]
218 │
219 │ ver = as-i64 raw_ver
220 │ entries_n = as-i64 raw_entries
221 │
222 │ pk = hex-to-bytes pk_hex
223 │ if err? pk [ return pk ]
224 │ salt = hex-to-bytes salt_hex
225 │ if err? salt [ return salt ]
226 │ nonce = hex-to-bytes nonce_hex
227 │ if err? nonce [ return nonce ]
228 │
229 │ aad = build-aad ver cipher kdf pk_hex salt_hex nonce_hex entries_n
230 │ manifest_msg = compute-manifest-digest aad ct_bytes
231 │
232 │ {
233 │ version = ver
234 │ cipher = cipher
235 │ kdf = kdf
236 │ pk = pk
237 │ salt = salt
238 │ nonce = nonce
239 │ mac_hex = mac_hex
240 │ entries_n = entries_n
241 │ aad = aad
242 │ ct_and_tag = ct_bytes
243 │ sig = sig_bytes
244 │ manifest_msg = manifest_msg
245 │ }
246 │ ]
247 │
248 │ verify-vault-manifest = fn [parsed map] bool [
249 │ kx/ed25519-verify parsed.pk parsed.manifest_msg parsed.sig
250 │ ]
251 │
252 │ decrypt-vault-entries = fn [parsed map, pass str] any [
253 │ keys = derive-keys pass parsed.salt
254 │ expected_mac = sha/hmac-sha256 keys.mac_key parsed.manifest_msg
255 │ stored_mac = hex-to-bytes parsed.mac_hex
256 │ if err? stored_mac [ return stored_mac ]
257 │ if not (sha/ct-eq expected_mac stored_mac) [
258 │ return (err 'vault: HMAC-SHA256 verification failed (wrong passphrase or tampered manifest)')
259 │ ]
260 │ pt = aead/aead-decrypt keys.enc_key parsed.nonce parsed.aad parsed.ct_and_tag
261 │ if err? pt [ return pt ]
262 │ dec = json/decode/or (bytes/to-str pt) [.none]
263 │ if err? dec or dec == .none or not (is-map? dec) [
264 │ return (err 'vault: corrupted plaintext payload')
265 │ ]
266 │ entries_val = json/get dec 'entries'
267 │ if err? entries_val or entries_val == .null or not (is-map? entries_val) [
268 │ return (err 'vault: corrupted plaintext payload')
269 │ ]
270 │ entries_val
271 │ ]
272 │
273 │ open-vault = fn [parsed map, pass str] any [
274 │ if not (verify-vault-manifest parsed) [
275 │ return (err 'vault: Ed25519 manifest signature verification failed')
276 │ ]
277 │ decrypt-vault-entries parsed pass
278 │ ]
279 │
280 │ resolve-demo-path = fn [] str [
281 │ tmp1 = os/getenv/or 'TEMP' ['']
282 │ tmp2 = if tmp1 == '' [ os/getenv/or 'TMP' [''] ] else [ tmp1 ]
283 │ if tmp2 == '' [
284 │ 'veko_vault_demo.pem'
285 │ ] else [
286 │ str/join [tmp2 '/veko_vault_demo.pem'] ''
287 │ ]
288 │ ]
289 │
290 │ default-passphrase = fn [] str [
291 │ env_pw = os/getenv/or 'VEKO_VAULT_PASSPHRASE' ['']
292 │ if env_pw == '' [ 'veko-vault-demo-passphrase' ] else [ env_pw ]
293 │ ]
294 │
295 │ run-self-demo = fn [] i64 [
296 │ demo_path = resolve-demo-path
297 │ pass = default-passphrase
298 │
299 │ // 1. `.secret` governance: VaultSecret + bytes/with-secret blocked from JSON egress
300 │ env_secret = os/getenv/secret/or 'VEKO_VAULT_KEY' ['veko-vault-secret-material']
301 │ vs = VaultSecret { name = 'master', value = env_secret }
302 │ mut sec_buf = bytes/with-secret 16b
303 │ bytes/push-all (mut sec_buf) (bytes/from-str 'master-key-bytes')
304 │ sec_box = [sec_buf]
305 │ fw_verdict = json/encode/or { key = sec_box[0] } ['secret-json-blocked']
306 │
307 │ // 2. Seal vault with 3 entries using HKDF-SHA256 + ChaCha20-Poly1305 + Ed25519
308 │ salt = random/bytes 16
309 │ nonce = random/bytes 12
310 │ entries = {
311 │ 'api.token' = 'tok_prod_veko_991'
312 │ 'db.dsn' = 'postgres://vault.local/app'
313 │ 'tls.pin' = 'sha256/veko-spki-pin'
314 │ }
315 │ sealed = seal-vault pass salt nonce entries .none
316 │ if err? sealed [
317 │ println (mold sealed)
318 │ return 1
319 │ ]
320 │ _ = os/write-file demo_path sealed.pem_text
321 │ exists_after_write = os/exists? demo_path
322 │
323 │ // 3. Reload PEM from disk/VFS, parse via `pem-to-block` + `parse-block`, verify & decrypt
324 │ raw_bytes = os/read-bytes demo_path
325 │ parsed = parse-vault-pem (bytes/to-str raw_bytes)
326 │ if err? parsed [
327 │ println (mold parsed)
328 │ return 1
329 │ ]
330 │
331 │ sig_ok = verify-vault-manifest parsed
332 │ if not sig_ok [
333 │ println 'err(vault: Ed25519 manifest signature verification failed)'
334 │ return 1
335 │ ]
336 │ opened = decrypt-vault-entries parsed pass
337 │ if err? opened [
338 │ println (mold opened)
339 │ return 1
340 │ ]
341 │
342 │ // 4. Tamper-detection suite:
343 │ // (a) Ed25519 manifest tamper (2nd verify call)
344 │ bad_msg = flip-first-byte parsed.manifest_msg
345 │ tamper_sig_ok = kx/ed25519-verify parsed.pk bad_msg parsed.sig
346 │
347 │ // (b) ChaCha20-Poly1305 ciphertext tamper
348 │ keys = derive-keys pass parsed.salt
349 │ bad_ct = flip-first-byte parsed.ct_and_tag
350 │ tamper_aead = aead/aead-decrypt/or keys.enc_key parsed.nonce parsed.aad bad_ct [.rejected]
351 │
352 │ // (c) Wrong passphrase rejection
353 │ wrong_keys = derive-keys 'wrong-passphrase' parsed.salt
354 │ wrong_aead = aead/aead-decrypt/or wrong_keys.enc_key parsed.nonce parsed.aad parsed.ct_and_tag [.rejected]
355 │
356 │ // 5. Scrub temporary demo file (no `os/remove` builtin; overwrite full byte length for Wasm CoW VFS)
357 │ scrub_hdr = '# veko-vault-demo-scrubbed\n'
358 │ orig_n = len raw_bytes
359 │ mut scrub_parts = [scrub_hdr]
360 │ mut scrub_cur = len scrub_hdr
361 │ while scrub_cur < orig_n [
362 │ push mut scrub_parts ' '
363 │ scrub_cur = scrub_cur + 1
364 │ ]
365 │ _ = os/write-file demo_path (str/join scrub_parts '')
366 │ scrubbed = bytes/to-str (os/read-bytes demo_path)
367 │ scrub_ok = not (str/contains? scrubbed 'BEGIN VEKO VAULT')
368 │
369 │ println (str/join ['vault-secret-mold=' (mold sec_buf) '|name=' vs.name] '')
370 │ println (str/join ['vault-secret-firewall=' fw_verdict] '')
371 │ println (str/join ['vault-sealed=exists:' (mold exists_after_write) ',entries:' (mold parsed.entries_n) ',cipher:' parsed.cipher] '')
372 │ println (str/join ['vault-ed25519-verify=' (mold sig_ok)] '')
373 │ println (str/join ['vault-unseal=api:' (json/get opened 'api.token') ',db:' (json/get opened 'db.dsn') ',tls:' (json/get opened 'tls.pin')] '')
374 │ println (str/join ['tamper-ed25519-rejected=' (mold (not tamper_sig_ok))] '')
375 │ println (str/join ['tamper-aead-rejected=' (mold (tamper_aead == .rejected))] '')
376 │ println (str/join ['wrong-pass-rejected=' (mold (wrong_aead == .rejected))] '')
377 │ println (str/join ['demo-scrubbed=' (mold scrub_ok)] '')
378 │ 0
379 │ ]
380 │
381 │ print-usage = fn [] i64 [
382 │ println 'Veko Encrypted Vault CLI (Ed25519 + ChaCha20-Poly1305 + PEM)'
383 │ println 'Usage:'
384 │ println ' init <vault.pem> [--pass <pw>]'
385 │ println ' set <vault.pem> <key> <value> [--pass <pw>]'
386 │ println ' get <vault.pem> <key> [--pass <pw>]'
387 │ println ' list <vault.pem> [--pass <pw>]'
388 │ println ' verify <vault.pem>'
389 │ println ' --help'
390 │ 0
391 │ ]
392 │
393 │ parse-cli-args = fn [args block] any [
394 │ mut pos = []
395 │ mut pass = default-passphrase
396 │ mut help = false
397 │ mut i = 0
398 │ while i < (len args) [
399 │ a = args[i]
400 │ if a == '--help' or a == '-h' [
401 │ help = true
402 │ i = i + 1
403 │ ] else [
404 │ if a == '--pass' [
405 │ if (i + 1) >= (len args) [
406 │ return (err 'vault: --pass requires a value')
407 │ ]
408 │ pass = args[i + 1]
409 │ i = i + 2
410 │ ] else [
411 │ push mut pos a
412 │ i = i + 1
413 │ ]
414 │ ]
415 │ ]
416 │ { pos = pos, pass = pass, help = help }
417 │ ]
418 │
419 │ run-cli = fn [args block] i64 [
420 │ cli = parse-cli-args args
421 │ if err? cli [
422 │ println (mold cli)
423 │ return 1
424 │ ]
425 │ if cli.help or (len cli.pos) == 0 [
426 │ return (print-usage)
427 │ ]
428 │ cmd = cli.pos[0]
429 │ pass = cli.pass
430 │
431 │ if cmd == 'init' [
432 │ if (len cli.pos) < 2 [
433 │ println 'error: init requires <vault.pem>'
434 │ return 1
435 │ ]
436 │ path = cli.pos[1]
437 │ salt = random/bytes 16
438 │ nonce = random/bytes 12
439 │ sealed = seal-vault pass salt nonce {} .none
440 │ if err? sealed [
441 │ println (mold sealed)
442 │ return 1
443 │ ]
444 │ _ = os/write-file path sealed.pem_text
445 │ println (str/join ['vault-init=ok|file=' path '|entries=0'] '')
446 │ return 0
447 │ ]
448 │
449 │ if cmd == 'verify' [
450 │ if (len cli.pos) < 2 [
451 │ println 'error: verify requires <vault.pem>'
452 │ return 1
453 │ ]
454 │ path = cli.pos[1]
455 │ if not (os/exists? path) [
456 │ println (str/join ['error: file not found: ' path] '')
457 │ return 1
458 │ ]
459 │ parsed = parse-vault-pem (bytes/to-str (os/read-bytes path))
460 │ if err? parsed [
461 │ println (mold parsed)
462 │ return 1
463 │ ]
464 │ ok = verify-vault-manifest parsed
465 │ println (str/join ['vault-verify=' (mold ok) '|entries=' (mold parsed.entries_n)] '')
466 │ if ok [ return 0 ] else [ return 1 ]
467 │ ]
468 │
469 │ if cmd == 'set' [
470 │ if (len cli.pos) < 4 [
471 │ println 'error: set requires <vault.pem> <key> <value>'
472 │ return 1
473 │ ]
474 │ path = cli.pos[1]
475 │ k = cli.pos[2]
476 │ v = cli.pos[3]
477 │ if not (os/exists? path) [
478 │ println (str/join ['error: file not found: ' path] '')
479 │ return 1
480 │ ]
481 │ parsed = parse-vault-pem (bytes/to-str (os/read-bytes path))
482 │ if err? parsed [
483 │ println (mold parsed)
484 │ return 1
485 │ ]
486 │ entries = open-vault parsed pass
487 │ if err? entries [
488 │ println (mold entries)
489 │ return 1
490 │ ]
491 │ updated = map/set entries k v
492 │ new_nonce = random/bytes 12
493 │ sealed = seal-vault pass parsed.salt new_nonce updated parsed.pk
494 │ if err? sealed [
495 │ println (mold sealed)
496 │ return 1
497 │ ]
498 │ _ = os/write-file path sealed.pem_text
499 │ println (str/join ['vault-set=' k '|entries=' (mold (len (map/keys updated)))] '')
500 │ return 0
501 │ ]
502 │
503 │ if cmd == 'get' [
504 │ if (len cli.pos) < 3 [
505 │ println 'error: get requires <vault.pem> <key>'
506 │ return 1
507 │ ]
508 │ path = cli.pos[1]
509 │ k = cli.pos[2]
510 │ if not (os/exists? path) [
511 │ println (str/join ['error: file not found: ' path] '')
512 │ return 1
513 │ ]
514 │ parsed = parse-vault-pem (bytes/to-str (os/read-bytes path))
515 │ if err? parsed [
516 │ println (mold parsed)
517 │ return 1
518 │ ]
519 │ entries = open-vault parsed pass
520 │ if err? entries [
521 │ println (mold entries)
522 │ return 1
523 │ ]
524 │ val = map/get/or entries k [.none]
525 │ if val == .none [
526 │ println (str/join ['vault-get=' k '|found=false'] '')
527 │ return 1
528 │ ]
529 │ println (str/join ['vault-get=' k '=' val] '')
530 │ return 0
531 │ ]
532 │
533 │ if cmd == 'list' [
534 │ if (len cli.pos) < 2 [
535 │ println 'error: list requires <vault.pem>'
536 │ return 1
537 │ ]
538 │ path = cli.pos[1]
539 │ if not (os/exists? path) [
540 │ println (str/join ['error: file not found: ' path] '')
541 │ return 1
542 │ ]
543 │ parsed = parse-vault-pem (bytes/to-str (os/read-bytes path))
544 │ if err? parsed [
545 │ println (mold parsed)
546 │ return 1
547 │ ]
548 │ entries = open-vault parsed pass
549 │ if err? entries [
550 │ println (mold entries)
551 │ return 1
552 │ ]
553 │ ks = map/keys entries
554 │ println (str/join ['vault-list=count:' (mold (len ks)) '|keys=' (str/join ks ',')] '')
555 │ return 0
556 │ ]
557 │
558 │ println (str/join ['error: unknown command ' cmd] '')
559 │ print-usage
560 │ ]
561 │
562 │ if (len os/args) == 0 [
563 │ _ = run-self-demo
564 │ ] else [
565 │ _ = run-cli os/args
566 │ ]Example 16: 16_query_dialect_engine.vk
Run command: veko -A examples/16_query_dialect_engine.vk
Example 16: Homoiconic Query & Stream Pipeline Dialect Engine (VQL) Demonstrates quote, compose / compose/deep, parse-block, cross-backend compile-time macros, typed struct records (TraceSpan, QueryPlan), struct/with, filter/map/reduce, match, /or, tail-recursive recur, and optional os/args latency threshold override. Track A (.vko) : veko compile --vko examples/16_query_dialect_engine.vk -o dist/16.vko ; veko run dist/16.vko Track C (Native) : veko compile --native examples/16_query_dialect_engine.vk -o dist/16.exe ; ./dist/16.exe
1 │ // Example 16: Homoiconic Query & Stream Pipeline Dialect Engine (VQL)
2 │ // Demonstrates `quote`, `compose` / `compose/deep`, `parse-block`, cross-backend compile-time
3 │ // `macro`s, typed `struct` records (`TraceSpan`, `QueryPlan`), `struct/with`, `filter`/`map`/`reduce`,
4 │ // `match`, `/or`, tail-recursive `recur`, and optional `os/args` latency threshold override.
5 │ //
6 │ // Track A (ORO VM) : veko run examples/16_query_dialect_engine.vk
7 │ // Track A (.vko) : veko compile --vko examples/16_query_dialect_engine.vk -o dist/16.vko ; veko run dist/16.vko
8 │ // Track B (Wasm 3) : veko run --wasm examples/16_query_dialect_engine.vk
9 │ // Track C (Native) : veko compile --native examples/16_query_dialect_engine.vk -o dist/16.exe ; ./dist/16.exe
10 │
11 │ use [j = json, str]
12 │
13 │ TraceSpan = struct {
14 │ id i64
15 │ svc str
16 │ region str = 'us-east'
17 │ severity u8 = 1
18 │ status i64 = 200
19 │ latency_ms i64
20 │ bytes_out i64
21 │ err_tag str = ''
22 │ }
23 │
24 │ QueryPlan = struct {
25 │ name str
26 │ svc str
27 │ min_ms i64
28 │ status_min i64
29 │ region str
30 │ limit i64
31 │ agg str = 'sum_bytes'
32 │ }
33 │
34 │ make-plan = fn [name str, svc str, min_ms i64, status_min i64, region str, limit i64] QueryPlan [
35 │ QueryPlan {
36 │ name = name
37 │ svc = svc
38 │ min_ms = min_ms
39 │ status_min = status_min
40 │ region = region
41 │ limit = limit
42 │ agg = 'sum_bytes'
43 │ }
44 │ ]
45 │
46 │ // Cross-backend safe compile-time macros: IntLitExpr args, flat compose output
47 │ sla-budget = macro [target_ms multiplier] [
48 │ compose [(target_ms) * (multiplier)]
49 │ ]
50 │
51 │ sla-floor = macro [base_ms margin_ms] [
52 │ compose [(base_ms) + (margin_ms)]
53 │ ]
54 │
55 │ // Declarative VQL query specification parsed via homoiconic `quote` + `parse-block`
56 │ vql-spec = quote [
57 │ name 'edge-5xx-slow'
58 │ from 'edge-gateway'
59 │ where .latency_gt 100
60 │ where .status_ge 500
61 │ where .region_eq 'eu-west'
62 │ limit 2
63 │ agg .sum_bytes
64 │ ]
65 │
66 │ compile-vql = fn [spec any] map [
67 │ mut qname = 'unnamed'
68 │ mut qsvc = ''
69 │ mut qlimit = 10
70 │ mut qagg = .count
71 │ mut clauses = []
72 │
73 │ ok = parse-block spec [
74 │ any [
75 │ ['name' nm = str!] [
76 │ qname = nm
77 │ ]
78 │ ['from' s = str!] [
79 │ qsvc = s
80 │ ]
81 │ ['where' op = enum! rhs = any!] [
82 │ push mut clauses { op = op, rhs = rhs }
83 │ ]
84 │ ['limit' n = int!] [
85 │ qlimit = n
86 │ ]
87 │ ['agg' a = enum!] [
88 │ qagg = a
89 │ ]
90 │ ]
91 │ ]
92 │
93 │ { ok = ok, name = qname, svc = qsvc, limit = qlimit, agg = qagg, clauses = clauses }
94 │ ]
95 │
96 │ // Typed predicate evaluation using `match` over enum clause opcodes
97 │ eval-clause = fn [row TraceSpan, clause any] bool [
98 │ op = clause.op
99 │ match op [
100 │ .latency_gt [ row.latency_ms > (as-i64 clause.rhs) ]
101 │ .status_ge [ row.status >= (as-i64 clause.rhs) ]
102 │ .region_eq [ row.region == clause.rhs ]
103 │ .svc_eq [ row.svc == clause.rhs ]
104 │ _ [ false ]
105 │ ]
106 │ ]
107 │
108 │ // Constant-stack tail recursion (`recur`) evaluating all `where` clauses for one row
109 │ row-matches-all = fn [row TraceSpan, clauses any, idx i64] bool [
110 │ if idx >= (len clauses) [ return true ]
111 │ if not (eval-clause row clauses[idx]) [ return false ]
112 │ recur row clauses (idx + 1)
113 │ ]
114 │
115 │ take-n = fn [rows any, limit i64] any [
116 │ n = len rows
117 │ if limit <= 0 or n == 0 [ return [] ]
118 │ end_i = if limit < n [ limit ] else [ n ]
119 │ rows[0..end_i]
120 │ ]
121 │
122 │ compute-agg = fn [rows any, agg_kind any] i64 [
123 │ match agg_kind [
124 │ .sum_bytes [
125 │ rows \ map fn [r] [r.bytes_out] \ reduce 0 fn [acc x] [acc + x]
126 │ ]
127 │ .max_latency [
128 │ rows \ map fn [r] [r.latency_ms] \ reduce 0 fn [acc x] [if x > acc [ x ] else [ acc ]]
129 │ ]
130 │ _ [
131 │ len rows
132 │ ]
133 │ ]
134 │ ]
135 │
136 │ // Sample telemetry stream constructed with `TraceSpan` defaults and `struct/with`
137 │ base_span = TraceSpan {
138 │ id = 1
139 │ svc = 'edge-gateway'
140 │ region = 'eu-west'
141 │ severity = as-u8/or 3 [as-u8 1]
142 │ status = 502
143 │ latency_ms = 145
144 │ bytes_out = 2400
145 │ err_tag = 'upstream-timeout'
146 │ }
147 │
148 │ stream = [
149 │ base_span
150 │ (base_span \ struct/with { id = 2, severity = 1, latency_ms = 65, status = 200, err_tag = '' })
151 │ (base_span \ struct/with { id = 3, region = 'us-east', latency_ms = 210, status = 503, bytes_out = 4100 })
152 │ (base_span \ struct/with { id = 4, severity = 5, latency_ms = 320, status = 504, bytes_out = 5120, err_tag = 'gateway-504' })
153 │ (base_span \ struct/with { id = 5, svc = 'auth-core', latency_ms = 180, status = 500, bytes_out = 1200 })
154 │ (base_span \ struct/with { id = 6, latency_ms = 260, status = 502, bytes_out = 3000, err_tag = 'bad-gateway' })
155 │ ]
156 │
157 │ // Optional CLI `os/args` latency override (`-- <min_ms>` or `min_ms`)
158 │ default_min_ms = sla-floor 80 20
159 │ cli_min_ms = if (len os/args) > 0 [
160 │ str/to-i64/or os/args[0] [default_min_ms]
161 │ ] else [
162 │ default_min_ms
163 │ ]
164 │
165 │ // 1. Compile and run declarative VQL program
166 │ compiled = compile-vql vql-spec
167 │ svc_filtered = if compiled.svc != '' [
168 │ stream \ filter fn [r] [r.svc == compiled.svc]
169 │ ] else [
170 │ stream
171 │ ]
172 │ matched_all = svc_filtered \ filter fn [r] [row-matches-all r compiled.clauses 0]
173 │ limited = take-n matched_all compiled.limit
174 │ agg_bytes = compute-agg limited compiled.agg
175 │
176 │ projected = limited \ map fn [r] [
177 │ str/join [(mold r.id) ':' r.svc '@' r.region ':' (mold r.status) ':' (mold r.latency_ms) 'ms'] ''
178 │ ]
179 │
180 │ // 2. Compile-time macro budget + typed `QueryPlan` + `struct/with` override
181 │ budget_ms = sla-budget 120 2
182 │ base_plan = make-plan 'sla-watchdog' 'edge-gateway' default_min_ms 500 'eu-west' 5
183 │ active_plan = base_plan \ struct/with { min_ms = cli_min_ms }
184 │
185 │ plan_matches = stream
186 │ \ filter fn [r] [r.svc == active_plan.svc and r.latency_ms > active_plan.min_ms and r.status >= active_plan.status_min and r.region == active_plan.region]
187 │ plan_max_lat = compute-agg plan_matches .max_latency
188 │ over_budget = plan_matches \ filter fn [r] [r.latency_ms > budget_ms]
189 │
190 │ // 3. Checked conversion fallback demonstration
191 │ bad_u8 = as-u8/or 999 [as-u8 255]
192 │
193 │ // 4. Diagnostic report AST via `compose/deep`
194 │ q_name = compiled.name
195 │ q_ok = compiled.ok
196 │ q_matched = len matched_all
197 │ q_returned = len limited
198 │ p_name = active_plan.name
199 │ p_breaches = len over_budget
200 │ report_ast = compose/deep [
201 │ vql (q_name) [
202 │ parsed (q_ok)
203 │ matched (q_matched)
204 │ returned (q_returned)
205 │ sum_bytes (agg_bytes)
206 │ ]
207 │ sla [
208 │ plan (p_name)
209 │ budget_ms (budget_ms)
210 │ breaches (p_breaches)
211 │ max_ms (plan_max_lat)
212 │ ]
213 │ ]
214 │
215 │ println (str/join ['vql-parsed=' (mold compiled.ok) '|name=' compiled.name '|clauses=' (mold (len compiled.clauses))] '')
216 │ println (str/join ['vql-matched=' (mold (len matched_all)) '|limited=' (mold (len limited)) '|sum-bytes=' (mold agg_bytes)] '')
217 │ println (str/join ['vql-rows=' (str/join projected ',')] '')
218 │ println (str/join ['macro-plan=' (j/encode active_plan)] '')
219 │ println (str/join ['sla-budget=' (mold budget_ms) '|breaches=' (mold (len over_budget)) '|max-ms=' (mold plan_max_lat) '|clamped-u8=' (mold bad_u8)] '')
220 │ println (str/join ['report-ast=' (mold report_ast)] '')Example 17: 17_stdlib_cli_fmt_and_collections.vk
Run command: veko -A examples/17_stdlib_cli_fmt_and_collections.vk
End-to-end demo of Veko 1.0's pure-.vk core standard library (0 capabilities): fmt, cli, testing, math, text, path, seq, coll, and rand.
1 │ // examples/17_stdlib_cli_fmt_and_collections.vk
2 │ // End-to-end demo of Veko 1.0's pure-`.vk` core standard library (0 capabilities):
3 │ // `fmt`, `cli`, `testing`, `math`, `text`, `path`, `seq`, `coll`, and `rand`.
4 │
5 │ use [
6 │ cli
7 │ coll
8 │ fmt
9 │ m = math
10 │ path
11 │ rand
12 │ seq
13 │ t = testing
14 │ text
15 │ ]
16 │
17 │ run-demo = fn [] i64 [
18 │ mut suite = t/new '17-stdlib-core'
19 │
20 │ // 1. Declarative CLI parsing (`lib/cli.vk`)
21 │ spec = cli/CliSpec {
22 │ name = 'node-ctl'
23 │ version = '1.0.0'
24 │ summary = 'Veko cluster control CLI'
25 │ flags = [
26 │ cli/FlagSpec { name = 'port', short = 'p', kind = .i64, default_val = 8443, help = 'Listen port' }
27 │ cli/FlagSpec { name = 'verbose', short = 'v', kind = .bool, default_val = false, help = 'Verbose logs' }
28 │ cli/FlagSpec { name = 'tag', short = 't', kind = .list, help = 'Repeatable label' }
29 │ ]
30 │ commands = [
31 │ cli/CmdSpec { name = 'deploy', summary = 'Deploy a service bundle', min_args = 1 }
32 │ ]
33 │ }
34 │ parsed = cli/parse spec ['deploy' '-v' '--port=9443' '-t' 'eu' '-t' 'prod' 'edge-gw.vkp']
35 │ _ = t/eq mut suite parsed.command 'deploy' 'cli subcommand'
36 │ _ = t/eq mut suite (cli/flag-i64 parsed 'port' 0) 9443 'cli port flag'
37 │ _ = t/ok mut suite (cli/flag-bool parsed 'verbose') 'cli verbose flag'
38 │ _ = t/eq mut suite (len (cli/flag-list parsed 'tag')) 2 'cli repeatable list flag'
39 │ _ = t/eq mut suite parsed.args[0] 'edge-gw.vkp' 'cli positional arg'
40 │ println (cli/render-help spec)
41 │ println ''
42 │
43 │ // 2. Formatting, units, radix, hexdump, & ASCII tables (`lib/fmt.vk`)
44 │ banner = fmt/template 'Deploying {app} ({size}) in {dur}' {
45 │ app = parsed.args[0]
46 │ size = (fmt/size 2621440)
47 │ dur = (fmt/dur 12500000)
48 │ }
49 │ println banner
50 │ _ = t/eq mut suite banner 'Deploying edge-gw.vkp (2.50 MiB) in 12.50 ms' 'fmt/template + units'
51 │ _ = t/eq mut suite (fmt/int-radix 255 16) 'ff' 'fmt/int-radix hex'
52 │ println (fmt/table ['Subsystem' 'Metric' 'Status'] [
53 │ ['math' (fmt/format 'pi={0} gcd={1}' [m/pi (m/gcd 84 36)]) 'OK']
54 │ ['text' (text/slugify 'Veko 1.0 Standard Library!') 'OK']
55 │ ['path' (path/confine '/srv/veko' 'bundles/edge-gw.vkp') 'OK']
56 │ ])
57 │
58 │ // 3. Math constants, checked arithmetic, bitops, & IEEE-754 transcendentals (`lib/math.vk`)
59 │ _ = t/eq mut suite (m/add-checked/or m/i64-max 1 [-1]) -1 'math checked overflow'
60 │ _ = t/eq mut suite (m/popcount 0xFF0F) 12 'math popcount'
61 │ _ = t/approx mut suite (m/sqrt 2.0) m/sqrt2 0.000000000001 'math sqrt(2)'
62 │ _ = t/approx mut suite (m/sin (m/pi / 2.0)) 1.0 0.000000000001 'math sin(pi/2)'
63 │ _ = t/approx mut suite (m/ln m/e) 1.0 0.000000000001 'math ln(e)'
64 │
65 │ // 4. Text & safe lexical path confinement (`lib/text.vk`, `lib/path.vk`)
66 │ _ = t/eq mut suite (text/slugify 'Hello, Veko 1.0!') 'hello-veko-1-0' 'text slugify'
67 │ _ = t/eq mut suite (text/utf8-len 'Veko') 4 'text utf8-len'
68 │ _ = t/eq mut suite (path/confine/or '/srv/data' '../../etc/passwd' ['blocked']) 'blocked' 'path traversal blocked'
69 │
70 │ // 5. Sequence algorithms (`lib/seq.vk`)
71 │ sorted = seq/sort [42 7 19 3 99 12]
72 │ _ = t/eq mut suite sorted [3 7 12 19 42 99] 'seq/sort'
73 │ _ = t/eq mut suite (seq/binary-search sorted 19) 3 'seq/binary-search'
74 │ _ = t/eq mut suite (seq/fold sorted 0 fn [acc, x] [ acc + x ]) 182 'seq/fold'
75 │
76 │ // 6. Collections: Set, Ring, Heap, LRU, Memo (`lib/coll.vk`)
77 │ s_a = coll/set-from ['api' 'auth' 'db']
78 │ s_b = coll/set-from ['db' 'edge']
79 │ _ = t/eq mut suite (coll/set-len (coll/set-union s_a s_b)) 4 'set union'
80 │ _ = t/ok mut suite (coll/set-has? (coll/set-intersect s_a s_b) 'db') 'set intersect'
81 │
82 │ mut ring = coll/ring-new 3
83 │ _ = coll/ring-push mut ring 'first'
84 │ _ = coll/ring-push mut ring 'second'
85 │ _ = t/eq mut suite (coll/ring-pop mut ring) 'first' 'ring FIFO pop'
86 │
87 │ mut pq = coll/heap-new
88 │ _ = coll/heap-push mut pq 50 'low'
89 │ _ = coll/heap-push mut pq 10 'urgent'
90 │ _ = coll/heap-push mut pq 30 'normal'
91 │ _ = t/eq mut suite (coll/heap-pop mut pq) 'urgent' 'min-heap pop'
92 │
93 │ mut lru = coll/lru-new 2
94 │ _ = coll/lru-put mut lru 'k1' 100
95 │ _ = coll/lru-put mut lru 'k2' 200
96 │ _ = coll/lru-get mut lru 'k1'
97 │ _ = coll/lru-put mut lru 'k3' 300
98 │ _ = t/ok mut suite ((not (coll/lru-has? lru 'k2')) and (coll/lru-has? lru 'k1')) 'lru eviction'
99 │
100 │ // 7. Deterministic PRNG & CSPRNG UUID v4 (`lib/rand.vk`)
101 │ mut rng = rand/seed 2026
102 │ mut deck = [1 2 3 4 5 6]
103 │ _ = rand/shuffle mut rng mut deck
104 │ uuid = rand/uuid-v4
105 │ _ = t/eq mut suite (len uuid) 36 'uuid-v4 length'
106 │ println (fmt/format 'Generated UUID v4: {0}' [uuid])
107 │
108 │ t/report suite
109 │ ]
110 │
111 │ res = run-demo
112 │ if err? res [
113 │ println (mold res)
114 │ res
115 │ ] else [
116 │ 0
117 │ ]Example 18: 18_io_streams_regex_and_codecs.vk
Run command: veko -A examples/18_io_streams_regex_and_codecs.vk
End-to-end demo of Veko 1.0's streams, pattern matchers, dialect engine, codecs, and compression: buf, io, glob, regex, dialect, codec/{wire,hex,url,csv,ini,vbin,cbor,http2}, and compress/deflate.
1 │ // examples/18_io_streams_regex_and_codecs.vk
2 │ // End-to-end demo of Veko 1.0's streams, pattern matchers, dialect engine, codecs, and compression:
3 │ // `buf`, `io`, `glob`, `regex`, `dialect`, `codec/{wire,hex,url,csv,ini,vbin,cbor,http2}`, and `compress/deflate`.
4 │
5 │ use [
6 │ bits
7 │ buf
8 │ cbor = codec/cbor
9 │ csv = codec/csv
10 │ d = dialect
11 │ def = compress/deflate
12 │ glob
13 │ h2 = codec/http2
14 │ hex = codec/hex
15 │ ini = codec/ini
16 │ io
17 │ re = regex
18 │ t = testing
19 │ url = codec/url
20 │ vbin = codec/vbin
21 │ wire = codec/wire
22 │ ]
23 │
24 │ run-demo = fn [] i64 [
25 │ mut suite = t/new '18-io-matchers-codecs-deflate'
26 │
27 │ // 1. ORO-native ByteReader/ByteWriter & Stream SchemeMux (`lib/buf.vk`, `lib/io.vk`)
28 │ mux = io/mux-default
29 │ mut src = io/mux-open mux 'mem://veko-stream-payload-2026'
30 │ mut dst = io/mem-stream (bytes/with-cap 0)
31 │ copied = io/copy mut src mut dst 8
32 │ _ = t/eq mut suite copied 24 'io/copy bytes'
33 │ _ = t/eq mut suite (bytes/to-str (io/read-all mut dst)) 'veko-stream-payload-2026' 'io mem-stream copy'
34 │
35 │ mut sb = buf/sb-new 32
36 │ _ = buf/sb-push mut sb 'veko:'
37 │ _ = buf/sb-push mut sb 'ok'
38 │ _ = t/eq mut suite (buf/sb-build sb) 'veko:ok' 'StringBuilder'
39 │
40 │ // 2. Glob & ReDoS-proof Thompson NFA Regex (`lib/glob.vk`, `lib/regex.vk`)
41 │ paths = ['lib/crypto/mlkem.vk' 'lib/codec/cbor.vk' 'docs/user/readme.md']
42 │ vk_files = glob/filter 'lib/**/*.vk' paths
43 │ _ = t/eq mut suite (len vk_files) 2 'glob ** filter'
44 │
45 │ rx_num = re/compile '[a-z]+=[0-9]+'
46 │ matches = re/find-all rx_num 'host=edge port=8443 retries=3'
47 │ _ = t/eq mut suite (len matches) 2 'regex find-all'
48 │ _ = t/eq mut suite matches[0].text 'port=8443' 'regex first match'
49 │
50 │ // 3. Homoiconic Dialect Rule Rewriter (`lib/dialect.vk`)
51 │ rules = [
52 │ d/Rule {
53 │ name = 'route'
54 │ pattern = [.route '$method' '$path' '$target']
55 │ transform = fn [b] [
56 │ {
57 │ method = (map/get b 'method')
58 │ path = (map/get b 'path')
59 │ target = (map/get b 'target')
60 │ }
61 │ ]
62 │ }
63 │ ]
64 │ compiled_routes = d/apply-rules [
65 │ [.route .get '/health' 'health-svc']
66 │ [.route .post '/events' 'ingest-svc']
67 │ ] rules
68 │ _ = t/eq mut suite (len compiled_routes) 2 'dialect rule count'
69 │ _ = t/eq mut suite compiled_routes[1].target 'ingest-svc' 'dialect binding extraction'
70 │
71 │ // 4. Schema-Driven Wire Packet Codec (`lib/codec/wire.vk`)
72 │ pkt_schema = [
73 │ wire/Field { name = 'magic', kind = .u16_be }
74 │ wire/Field { name = 'seq', kind = .varint }
75 │ wire/Field { name = 'node', kind = .str_u16_be }
76 │ ]
77 │ pkt_bytes = wire/pack pkt_schema { magic = 0x564b, seq = 4096, node = 'eu-west-1' }
78 │ pkt_dec = wire/unpack pkt_schema pkt_bytes
79 │ _ = t/eq mut suite (map/get pkt_dec 'magic') 0x564b 'wire magic'
80 │ _ = t/eq mut suite (map/get pkt_dec 'seq') 4096 'wire varint'
81 │ _ = t/eq mut suite (map/get pkt_dec 'node') 'eu-west-1' 'wire str'
82 │
83 │ // 5. Text & Structured Codecs: Hex, URL, CSV, INI, VBIN, CBOR, HTTP/2 + HPACK
84 │ _ = t/eq mut suite (hex/encode (bytes/from-str 'OK')) '4f4b' 'codec/hex'
85 │ u = url/parse 'https://api.veko.dev:8443/v1/items?env=prod&limit=50#top'
86 │ q = url/parse-query u.query
87 │ _ = t/eq mut suite u.host 'api.veko.dev' 'url host'
88 │ _ = t/eq mut suite (map/get q 'limit') '50' 'url query'
89 │
90 │ csv_recs = csv/parse-records 'id,region\n1,us-east\n2,eu-central'
91 │ _ = t/eq mut suite (map/get csv_recs[1] 'region') 'eu-central' 'codec/csv'
92 │
93 │ ini_cfg = ini/parse '[db]\nhost = 10.0.0.5\nport = 5432'
94 │ _ = t/eq mut suite (ini/get ini_cfg 'db' 'port') '5432' 'codec/ini'
95 │
96 │ payload_obj = { ok = true, count = -99, empty = .null, tags = ['pq' 'oro'] }
97 │ vbin_dec = vbin/decode (vbin/encode payload_obj)
98 │ cbor_dec = cbor/decode (cbor/encode payload_obj)
99 │ _ = t/eq mut suite (map/get vbin_dec 'empty') .null 'vbin .null roundtrip'
100 │ _ = t/eq mut suite (map/get cbor_dec 'count') -99 'cbor negative int roundtrip'
101 │
102 │ hpack_blk = h2/hpack-encode [
103 │ h2/Header { name = ':method', value = 'GET' }
104 │ h2/Header { name = ':path', value = '/v1/status' }
105 │ h2/Header { name = 'x-proto', value = 'h2' }
106 │ ]
107 │ h2_frame = h2/encode-frame (h2/Frame {
108 │ ftype = h2/frame-headers
109 │ flags = h2/flag-end-headers
110 │ stream_id = 3
111 │ payload = hpack_blk
112 │ })
113 │ h2_dec = h2/decode-frame h2_frame
114 │ h2_hdrs = h2/hpack-decode h2_dec.payload
115 │ _ = t/eq mut suite h2_dec.stream_id 3 'http2 stream id'
116 │ _ = t/eq mut suite h2_hdrs[1].value '/v1/status' 'http2 HPACK decode'
117 │
118 │ // 6. RFC 1951 DEFLATE, RFC 1950 zlib, & RFC 1952 gzip (`lib/compress/deflate.vk`)
119 │ raw_txt = bytes/from-str 'veko zero-trust sandbox runtime veko zero-trust sandbox runtime veko zero-trust sandbox runtime'
120 │ gz = def/gzip-compress raw_txt
121 │ zl = def/zlib-compress raw_txt
122 │ _ = t/ok mut suite ((len gz) < (len raw_txt)) 'gzip shrinks repetitive payload'
123 │ _ = t/eq mut suite (def/gzip-decompress gz) raw_txt 'gzip roundtrip'
124 │ _ = t/eq mut suite (def/zlib-decompress zl) raw_txt 'zlib roundtrip'
125 │ _ = t/eq mut suite (bits/crc32 (bytes/from-str '123456789')) 0xcbf43926 'CRC-32 IEEE vector'
126 │
127 │ println (str/join ['Compressed ' (mold (len raw_txt)) ' B -> ' (mold (len gz)) ' B (gzip) / ' (mold (len zl)) ' B (zlib)'] '')
128 │ t/report suite
129 │ ]
130 │
131 │ res = run-demo
132 │ if err? res [
133 │ println (mold res)
134 │ res
135 │ ] else [
136 │ 0
137 │ ]Example 19: 19_modern_crypto_and_sealed_vault.vk
Run command: veko -A examples/19_modern_crypto_and_sealed_vault.vk
End-to-end demo of Veko 1.0's pure-.vk classical cryptography & sealed envelope vault: SHA3-256/SHAKE256, BLAKE2b, SHA-384/HKDF-SHA384, constant-time AES-256-GCM, XChaCha20-Poly1305 (24-byte nonce), PBKDF2-HMAC-SHA256, RFC 9106 Argon2id, RFC 6979 ECDSA P-256 signing, and crypto/seal (pub sealed Sealed + RAII zeroization).
1 │ // examples/19_modern_crypto_and_sealed_vault.vk
2 │ // End-to-end demo of Veko 1.0's pure-`.vk` classical cryptography & sealed envelope vault:
3 │ // SHA3-256/SHAKE256, BLAKE2b, SHA-384/HKDF-SHA384, constant-time AES-256-GCM,
4 │ // XChaCha20-Poly1305 (24-byte nonce), PBKDF2-HMAC-SHA256, RFC 9106 Argon2id,
5 │ // RFC 6979 ECDSA P-256 signing, and `crypto/seal` (`pub sealed Sealed` + RAII zeroization).
6 │
7 │ use [
8 │ aes = crypto/aes
9 │ b2 = crypto/blake
10 │ cc = crypto/chacha20
11 │ hex = codec/hex
12 │ kdf = crypto/kdf
13 │ s2 = crypto/sha256
14 │ s3 = crypto/sha3
15 │ seal = crypto/seal
16 │ sig = crypto/sig
17 │ t = testing
18 │ ]
19 │
20 │ run-demo = fn [] i64 [
21 │ mut suite = t/new '19-modern-crypto-and-seal'
22 │
23 │ // 1. Modern Hash Families: SHA3-256, SHAKE256, BLAKE2b-256, SHA-384
24 │ msg = bytes/from-str 'veko-1.0-crypto-audit'
25 │ d_sha3 = s3/sha3-256 msg
26 │ d_xof = s3/shake256 msg 48
27 │ d_b2 = b2/blake2b-256 msg
28 │ d_s384 = s2/sha384 msg
29 │ _ = t/eq mut suite (len d_sha3) 32 'SHA3-256 length'
30 │ _ = t/eq mut suite (len d_xof) 48 'SHAKE256 48-byte XOF length'
31 │ _ = t/eq mut suite (len d_b2) 32 'BLAKE2b-256 length'
32 │ _ = t/eq mut suite (len d_s384) 48 'SHA-384 length'
33 │ println (str/join ['SHA3-256 : ' (hex/encode d_sha3)] '')
34 │ println (str/join ['BLAKE2b : ' (hex/encode d_b2)] '')
35 │
36 │ // 2. Password & Key Derivation: PBKDF2-HMAC-SHA256 + RFC 9106 Argon2id + HKDF-SHA384
37 │ pw = bytes/from-str 'master-passphrase'
38 │ salt = bytes/from-str 'veko-vault-salt!'
39 │ mut vault_key = kdf/argon2id pw salt 8 1 32
40 │ pbk = kdf/pbkdf2-sha256 pw salt 4 32
41 │ prk384 = s2/hkdf-sha384-extract salt vault_key
42 │ sub32 = s2/hkdf-sha384-expand prk384 (bytes/from-str 'xchacha-subkey') 32
43 │ _ = t/eq mut suite (len vault_key) 32 'Argon2id 32-byte key'
44 │ _ = t/eq mut suite (len pbk) 32 'PBKDF2-SHA256 32-byte key'
45 │ _ = t/eq mut suite (len sub32) 32 'HKDF-SHA384 subkey'
46 │
47 │ // 3. AEAD Ciphers: Constant-Time AES-256-GCM & 24-Byte-Nonce XChaCha20-Poly1305
48 │ aad = bytes/from-str 'tenant=prod;v=1'
49 │ pt = bytes/from-str 'db_password=super-secret-value'
50 │ iv12 = random/bytes 12
51 │ ct_gcm = aes/gcm-encrypt vault_key iv12 pt aad
52 │ dec_gcm = aes/gcm-decrypt vault_key iv12 ct_gcm aad
53 │ _ = t/eq mut suite dec_gcm pt 'AES-256-GCM roundtrip'
54 │
55 │ iv24 = random/bytes 24
56 │ ct_xcc = cc/xchacha20-poly1305-encrypt sub32 iv24 aad pt
57 │ dec_xcc = cc/xchacha20-poly1305-decrypt sub32 iv24 aad ct_xcc
58 │ _ = t/eq mut suite dec_xcc pt 'XChaCha20-Poly1305 roundtrip'
59 │
60 │ // 4. Sealed Envelope (`pub sealed Sealed`) + Portable VKSL Wire + RAII Zeroization
61 │ env = seal/encrypt vault_key pt aad
62 │ wire_env = seal/to-bytes env
63 │ restored = seal/from-bytes wire_env
64 │ opened_len = seal/with-open restored vault_key fn [secret_pt] [ len secret_pt ]
65 │ _ = t/eq mut suite opened_len (len pt) 'seal/with-open RAII roundtrip'
66 │ _ = bytes/zeroize! mut vault_key
67 │
68 │ // 5. ECDSA P-256 Deterministic Signing (RFC 6979) & Verification
69 │ priv = bytes/fill 32 0x55
70 │ pubk = sig/ecdsa-p256-pubkey priv
71 │ cert_sig = sig/ecdsa-p256-sign priv wire_env
72 │ _ = t/ok mut suite (sig/ecdsa-p256-verify pubk wire_env cert_sig) 'ECDSA P-256 sign/verify'
73 │ _ = t/ok mut suite (not (sig/ecdsa-p256-verify pubk (bytes/from-str 'forged') cert_sig)) 'ECDSA P-256 tamper reject'
74 │ println (str/join ['Sealed VKSL envelope (' (mold (len wire_env)) ' B) signed with ECDSA P-256 (' (mold (len cert_sig)) ' B DER)'] '')
75 │
76 │ t/report suite
77 │ ]
78 │
79 │ res = run-demo
80 │ if err? res [
81 │ println (mold res)
82 │ res
83 │ ] else [
84 │ 0
85 │ ]Example 20: 20_post_quantum_nist_pqc.vk
Run command: veko -A examples/20_post_quantum_nist_pqc.vk
End-to-end demo of Veko 1.0's pure-.vk NIST Post-Quantum Cryptography standards: - FIPS 203: ML-KEM-512 & ML-KEM-768 (lattice key encapsulation + implicit rejection) - FIPS 204: ML-DSA-44 & ML-DSA-65 (lattice digital signatures) - FIPS 205: SLH-DSA-SHAKE-128f (stateless hash-based signatures) Combines ML-KEM-768 shared secret establishment with crypto/seal AES-256-GCM sealing.
1 │ // examples/20_post_quantum_nist_pqc.vk
2 │ // End-to-end demo of Veko 1.0's pure-`.vk` NIST Post-Quantum Cryptography standards:
3 │ // - FIPS 203: ML-KEM-512 & ML-KEM-768 (lattice key encapsulation + implicit rejection)
4 │ // - FIPS 204: ML-DSA-44 & ML-DSA-65 (lattice digital signatures)
5 │ // - FIPS 205: SLH-DSA-SHAKE-128f (stateless hash-based signatures)
6 │ // Combines ML-KEM-768 shared secret establishment with `crypto/seal` AES-256-GCM sealing.
7 │
8 │ use [
9 │ dsa = crypto/mldsa
10 │ hex = codec/hex
11 │ kem = crypto/mlkem
12 │ seal = crypto/seal
13 │ slh = crypto/slhdsa
14 │ t = testing
15 │ ]
16 │
17 │ run-demo = fn [] i64 [
18 │ mut suite = t/new '20-nist-post-quantum-crypto'
19 │
20 │ // 1. FIPS 203 ML-KEM-768 Key Encapsulation + Implicit Rejection + Sealed Envelope
21 │ kp_kem = kem/keygen .mlkem768
22 │ enc = kem/encaps .mlkem768 kp_kem.ek
23 │ ss_bob = kem/decaps .mlkem768 kp_kem.dk enc.ciphertext
24 │ _ = t/eq mut suite (len kp_kem.ek) 1184 'ML-KEM-768 ek size'
25 │ _ = t/eq mut suite (len enc.ciphertext) 1088 'ML-KEM-768 ciphertext size'
26 │ _ = t/eq mut suite ss_bob enc.shared_secret 'ML-KEM-768 shared secret agreement'
27 │
28 │ // Verify FIPS 203 implicit rejection on a 1-bit tampered ciphertext
29 │ mut bad_ct = bytes/with-cap (len enc.ciphertext)
30 │ _ = bytes/push-all mut bad_ct enc.ciphertext
31 │ _ = bytes/set mut bad_ct 0 (bad_ct[0] ^ 0x01)
32 │ ss_rej = kem/decaps .mlkem768 kp_kem.dk bad_ct
33 │ _ = t/neq mut suite ss_rej enc.shared_secret 'ML-KEM-768 implicit rejection'
34 │
35 │ // Seal a payload under the ML-KEM-768 post-quantum shared secret
36 │ pq_env = seal/encrypt enc.shared_secret (bytes/from-str 'quantum-resistant-payload') (bytes/from-str 'mlkem768')
37 │ pt_len = seal/with-open pq_env ss_bob fn [pt] [ len pt ]
38 │ _ = t/eq mut suite pt_len 25 'PQ-sealed envelope unseal'
39 │ println (str/join ['ML-KEM-768 : ek=' (mold (len kp_kem.ek)) ' B, ct=' (mold (len enc.ciphertext)) ' B, ss=' (hex/encode ss_bob[0..8]) '...'] '')
40 │
41 │ // 2. FIPS 204 ML-DSA-65 Lattice Digital Signature
42 │ kp_dsa = dsa/keygen .mldsa65
43 │ doc = bytes/from-str 'Veko 1.0 signed software release manifest'
44 │ sig_dsa = dsa/sign .mldsa65 kp_dsa.sk doc
45 │ _ = t/eq mut suite (len kp_dsa.pk) 1952 'ML-DSA-65 pk size'
46 │ _ = t/eq mut suite (len sig_dsa) 3309 'ML-DSA-65 sig size'
47 │ _ = t/ok mut suite (dsa/verify .mldsa65 kp_dsa.pk doc sig_dsa) 'ML-DSA-65 verify'
48 │ _ = t/ok mut suite (not (dsa/verify .mldsa65 kp_dsa.pk (bytes/from-str 'forged') sig_dsa)) 'ML-DSA-65 tamper reject'
49 │ println (str/join ['ML-DSA-65 : pk=' (mold (len kp_dsa.pk)) ' B, sig=' (mold (len sig_dsa)) ' B (verified)'] '')
50 │
51 │ // 3. FIPS 205 SLH-DSA-SHAKE-128f Stateless Hash-Based Signature
52 │ kp_slh = slh/keygen .shake_128f
53 │ sig_slh = slh/sign .shake_128f kp_slh.sk doc
54 │ _ = t/eq mut suite (len kp_slh.pk) 32 'SLH-DSA-128f pk size'
55 │ _ = t/ok mut suite (slh/verify .shake_128f kp_slh.pk doc sig_slh) 'SLH-DSA-128f verify'
56 │ _ = t/ok mut suite (not (slh/verify .shake_128f kp_slh.pk (bytes/from-str 'forged') sig_slh)) 'SLH-DSA-128f tamper reject'
57 │ println (str/join ['SLH-DSA-128f : pk=' (mold (len kp_slh.pk)) ' B, sig=' (mold (len sig_slh)) ' B (verified)'] '')
58 │
59 │ t/report suite
60 │ ]
61 │
62 │ res = run-demo
63 │ if err? res [
64 │ println (mold res)
65 │ res
66 │ ] else [
67 │ 0
68 │ ]Example 21: 21_io_streams_dns_and_pqc_tls.vk
Run command: veko -A examples/21_io_streams_dns_and_pqc_tls.vk
Example 21: Connected I/O Streams, DNS Wire Codec, Hybrid Post-Quantum TLS 1.3 (X25519MLKEM768) & HTTP/2 Demonstrates Phase 3A/3B libraries: rand/uuid-v7, io/fs, io/open, net/dns, hybrid post-quantum TLS 1.3 (0x11EC = X25519 + FIPS 203 ML-KEM-768) with ALPN 'h2', and RFC 9113 net/http2 RPC over tls13/tls-stream. Track C (Native) : veko compile --native examples/21_io_streams_dns_and_pqc_tls.vk -o dist/21.exe ; ./dist/21.exe
1 │ // Example 21: Connected I/O Streams, DNS Wire Codec, Hybrid Post-Quantum TLS 1.3 (X25519MLKEM768) & HTTP/2
2 │ // Demonstrates Phase 3A/3B libraries: `rand/uuid-v7`, `io/fs`, `io/open`, `net/dns`,
3 │ // hybrid post-quantum TLS 1.3 (`0x11EC` = X25519 + FIPS 203 ML-KEM-768) with ALPN `'h2'`,
4 │ // and RFC 9113 `net/http2` RPC over `tls13/tls-stream`.
5 │ //
6 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/21_io_streams_dns_and_pqc_tls.vk
7 │ // Track B (Wasm 3) : veko run --wasm --check-slabs --fuel=0 --allow-net --allow-listen --allow-private-net --allow-fs=. examples/21_io_streams_dns_and_pqc_tls.vk
8 │ // Track C (Native) : veko compile --native examples/21_io_streams_dns_and_pqc_tls.vk -o dist/21.exe ; ./dist/21.exe
9 │
10 │ use [
11 │ io
12 │ ifs = io/fs
13 │ iopen = io/open
14 │ rnd = rand
15 │ dns = net/dns
16 │ pem = codec/pem
17 │ sha = crypto/sha256
18 │ x509 = crypto/x509
19 │ tls13 = net/tls13
20 │ h2 = net/http2
21 │ ]
22 │
23 │ // 1. Time-ordered RFC 9562 UUID v7 backed by `time/unix`
24 │ u1 = rnd/uuid-v7
25 │ u2 = rnd/uuid-v7
26 │ if (len u1) != 36 or (len u2) != 36 or u1[14..15] != '7' [
27 │ err 'example21: invalid UUID v7'
28 │ ]
29 │ println (str/join ['uuid7=' u1] '')
30 │
31 │ // 2. Positioned `io/fs` + unified `io/open` (`mem://` and `file://`)
32 │ tmp_path = str/join [(os/temp-dir) '/veko_ex21_stream.dat'] ''
33 │ _ = os/remove/or tmp_path [.ok]
34 │ defer [ _ = os/remove/or tmp_path [.ok] ]
35 │
36 │ mut wf = ifs/open-write tmp_path
37 │ _ = io/write-all mut wf (bytes/from-str 'veko-phase3-io-stream')
38 │ _ = ifs/sync wf
39 │ _ = io/close mut wf
40 │
41 │ mut ms = iopen/open 'mem://hello-veko'
42 │ mem_txt = bytes/to-str (io/read-all mut ms)
43 │ mut fs_st = iopen/open (str/join ['file://' tmp_path] '')
44 │ file_txt = bytes/to-str (io/read-all mut fs_st)
45 │ _ = io/close mut fs_st
46 │ if mem_txt != 'hello-veko' or file_txt != 'veko-phase3-io-stream' [
47 │ err 'example21: io/open mismatch'
48 │ ]
49 │ println (str/join ['io=' mem_txt '|' file_txt] '')
50 │
51 │ // 3. Pure-Veko RFC 1035 DNS wire codec + `/etc/hosts` & `net/resolve`
52 │ qwire = dns/encode-query 0x2026 'api.veko.dev' dns/TYPE-A
53 │ hosts = dns/parse-hosts '127.0.0.1 localhost api.veko.local\n'
54 │ local_ips = net/resolve 'localhost'
55 │ if (len qwire) < 20 or (len local_ips) == 0 or not (map/has? hosts 'api.veko.local') [
56 │ err 'example21: dns/resolve failed'
57 │ ]
58 │ println (str/join ['dns=q' (mold (len qwire)) 'B|localhost=' (str/append local_ips[0] '')] '')
59 │
60 │ // 4. Live loopback Hybrid Post-Quantum TLS 1.3 (X25519MLKEM768) + ALPN 'h2' + HTTP/2
61 │ ca_seed = sha/sha256 (bytes/from-str 'veko-ex21-pqc-ca')
62 │ leaf_seed = sha/sha256 (bytes/from-str 'veko-ex21-pqc-leaf')
63 │ ca_der = x509/mint-ed25519-cert {
64 │ issuer_cn = 'Veko PQC Root', subject_cn = 'Veko PQC Root', is_ca = true
65 │ subject_seed = ca_seed, signer_seed = ca_seed, serial = 101
66 │ }
67 │ leaf_der = x509/mint-ed25519-cert {
68 │ issuer_cn = 'Veko PQC Root', subject_cn = 'pqc.veko.local', is_ca = false
69 │ san_dns = ['pqc.veko.local'], san_ips = ['127.0.0.1']
70 │ subject_seed = leaf_seed, signer_seed = ca_seed, serial = 102
71 │ }
72 │ roots_pem = pem/pem-encode 'CERTIFICATE' ca_der
73 │
74 │ ln = net/listen-tcp .ip '127.0.0.1:0'
75 │ port = str/to-i64 (str/split (net/addr ln) ':')[1]
76 │ done_ch = chan/new 1
77 │
78 │ srv = spawn [
79 │ sock = net/accept ln
80 │ mut sconn = tls13/server-handshake sock [leaf_der ca_der] leaf_seed
81 │ mut tst = tls13/tls-stream sconn
82 │ mut h2s = h2/server-accept mut tst
83 │ req = h2/read-request mut h2s
84 │ reply = str/join ['pqc-h2:' req.method ':' req.path ':group=' sconn.group ':alpn=' sconn.alpn] ''
85 │ _ = h2/write-response mut h2s req.stream_id 200 { 'content-type' = 'text/plain' } (bytes/from-str reply)
86 │ _ = chan/recv done_ch
87 │ mut s_st = h2s.stream
88 │ _ = io/close mut s_st
89 │ sconn.group
90 │ ]
91 │
92 │ mut cconn = tls13/connect '127.0.0.1' port {
93 │ server_name = 'pqc.veko.local'
94 │ roots_pem = roots_pem
95 │ alpn = 'h2'
96 │ pqc = true
97 │ }
98 │ mut ctst = tls13/tls-stream cconn
99 │ mut h2c = h2/client-open mut ctst
100 │ resp = h2/request mut h2c 'GET' '/v1/quantum' 'pqc.veko.local' {} (bytes/with-cap 0)
101 │ _ = chan/send done_ch .ok
102 │ mut c_st = h2c.stream
103 │ _ = io/close mut c_st
104 │ srv_group = task/await srv
105 │ _ = net/close ln
106 │
107 │ if err? resp [
108 │ err (str/join ['example21: HTTP/2 request failed: ' (mold resp)] '')
109 │ ]
110 │ body_txt = bytes/to-str resp.body
111 │ if resp.status != 200 or cconn.group != 'X25519MLKEM768' or srv_group != 'X25519MLKEM768' or cconn.alpn != 'h2' [
112 │ err (str/join ['example21: PQC TLS1.3 + HTTP/2 mismatch: status=' (mold resp.status) ' group=' (mold cconn.group)] '')
113 │ ]
114 │ println (str/join ['pqc_h2=' (mold resp.status) '|' body_txt] '')Example 22: 22_web_server_websocket_and_jwt.vk
Run command: veko -A examples/22_web_server_websocket_and_jwt.vk
Example 22: Web Micro-Framework, Post-Quantum JWT / OAuth2 PKCE & RFC 6455 WebSockets Demonstrates lib/auth/oauth2, lib/auth/jwt (HS256, EdDSA, ML-DSA-65), lib/web (router, middleware, JSON, SSE, multipart, static files), and live loopback lib/net/websocket upgrade + frame echo. Track C (Native) : veko compile --native examples/22_web_server_websocket_and_jwt.vk -o dist/22.exe ; ./dist/22.exe
1 │ // Example 22: Web Micro-Framework, Post-Quantum JWT / OAuth2 PKCE & RFC 6455 WebSockets
2 │ // Demonstrates `lib/auth/oauth2`, `lib/auth/jwt` (HS256, EdDSA, ML-DSA-65),
3 │ // `lib/web` (router, middleware, JSON, SSE, multipart, static files), and live loopback
4 │ // `lib/net/websocket` upgrade + frame echo.
5 │ //
6 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/22_web_server_websocket_and_jwt.vk
7 │ // Track B (Wasm 3) : veko run --wasm --check-slabs --fuel=0 --allow-net --allow-listen --allow-private-net examples/22_web_server_websocket_and_jwt.vk
8 │ // Track C (Native) : veko compile --native examples/22_web_server_websocket_and_jwt.vk -o dist/22.exe ; ./dist/22.exe
9 │
10 │ use [
11 │ io
12 │ inet = io/net
13 │ h1 = codec/http1
14 │ x25 = crypto/x25519
15 │ dsa = crypto/mldsa
16 │ jwt = auth/jwt
17 │ oa = auth/oauth2
18 │ web
19 │ ws = net/websocket
20 │ ]
21 │
22 │ // 1. OAuth 2.0 PKCE S256 flow
23 │ pkce = oa/generate-pkce
24 │ cfg = oa/OAuthConfig {
25 │ client_id = 'veko-portal'
26 │ auth_url = 'https://auth.veko.local/authorize'
27 │ token_url = 'https://auth.veko.local/token'
28 │ redirect_uri = 'http://127.0.0.1:8080/callback'
29 │ scope = 'openid api'
30 │ }
31 │ state_tok = oa/generate-state
32 │ auth_u = oa/authorize-url cfg state_tok pkce.challenge
33 │ if not (oa/verify-pkce pkce.verifier pkce.challenge) or not (str/contains? auth_u 'code_challenge_method=S256') [
34 │ err 'example22: oauth2 pkce failed'
35 │ ]
36 │ println (str/join ['oauth2_pkce=ok|method=' pkce.method] '')
37 │
38 │ // 2. JWT signing & verification: HS256, EdDSA (Ed25519), and Post-Quantum ML-DSA-65
39 │ now_s = (time/unix) / 1000000000
40 │ claims = { sub = 'alice', iss = 'veko.local', aud = 'api', nbf = now_s - 60, exp = now_s + 3600 }
41 │ c_opts = jwt/ClaimOpts { issuer = 'veko.local', audience = 'api', leeway_sec = 5 }
42 │
43 │ hs_key = bytes/from-str 'veko-ex22-hmac-signing-key-32byte'
44 │ hs_tok = jwt/sign-hs256 hs_key claims
45 │ hs_dec = jwt/verify-hs256 hs_tok hs_key
46 │ _ = jwt/validate-claims hs_dec.claims c_opts
47 │
48 │ ed_seed = bytes/from-str 'ed25519-demo-seed-0123456789abcd'
49 │ ed_pk = x25/ed25519-pubkey ed_seed
50 │ ed_tok = jwt/sign-eddsa ed_seed claims
51 │ ed_dec = jwt/verify-eddsa ed_tok ed_pk
52 │
53 │ pq_kp = dsa/keygen .mldsa65
54 │ pq_tok = jwt/sign-mldsa65 pq_kp.sk claims
55 │ pq_dec = jwt/verify-mldsa65 pq_tok pq_kp.pk
56 │ if hs_dec.claims.sub != 'alice' or ed_dec.claims.sub != 'alice' or pq_dec.claims.sub != 'alice' [
57 │ err 'example22: jwt verification failed'
58 │ ]
59 │ println (str/join ['jwt=HS256+EdDSA+ML-DSA-65|sub=' pq_dec.claims.sub] '')
60 │
61 │ // 3. `lib/web` HTTP/1.1 router, middleware, JWT guard, SSE & multipart
62 │ // Test multipart form-data & SSE formatting directly
63 │ mp_body = bytes/from-str '--vkb\r\nContent-Disposition: form-data; name="doc"; filename="a.txt"\r\nContent-Type: text/plain\r\n\r\nveko-upload\r\n--vkb--\r\n'
64 │ mp_parts = web/parse-multipart mp_body 'vkb'
65 │ sse_txt = web/sse-event 'tick' '{"n":1}' '1'
66 │ if (len mp_parts) != 1 or mp_parts[0].filename != 'a.txt' or (bytes/to-str mp_parts[0].data) != 'veko-upload' or not (str/contains? sse_txt 'event: tick') [
67 │ err 'example22: multipart/sse parse failed'
68 │ ]
69 │
70 │ // Serve live HTTP/1.1 request over loopback TCP inside an isolated `spawn` worker
71 │ wln = net/listen-tcp .ip '127.0.0.1:0'
72 │ wport = str/to-i64 (str/split (net/addr wln) ':')[1]
73 │
74 │ wsrv = spawn [
75 │ mut app = web/new-app
76 │ web/use-security-headers mut app
77 │ web/get mut app '/api/users/:id' fn [req web/Request] web/Response [
78 │ auth_hdr = web/header req 'Authorization' ''
79 │ btok = jwt/parse-bearer/or auth_hdr [ return (web/unauthorized 'missing bearer') ]
80 │ ver = jwt/verify-hs256/or btok hs_key [ return (web/unauthorized 'bad token') ]
81 │ web/json-resp 200 {
82 │ id = web/param req 'id' ''
83 │ viewer = ver.claims.sub
84 │ role = web/query-get req 'role' 'member'
85 │ }
86 │ ]
87 │ r = web/serve-once wln app
88 │ r.status
89 │ ]
90 │
91 │ mut cli_st = inet/dial-tcp '127.0.0.1' wport
92 │ req_wire = h1/encode-request 'GET' '/api/users/42?role=architect' {
93 │ Host = '127.0.0.1'
94 │ Authorization = oa/bearer-header hs_tok
95 │ } (bytes/with-cap 0)
96 │ _ = io/write-all mut cli_st req_wire
97 │ raw_resp = io/read-all mut cli_st
98 │ _ = io/close mut cli_st
99 │ srv_status = task/await wsrv
100 │ _ = net/close wln
101 │
102 │ dec_resp = h1/decode-response raw_resp
103 │ resp_json = json/decode (bytes/to-str dec_resp.body)
104 │ if srv_status != 200 or dec_resp.status != 200 or resp_json.id != '42' or resp_json.viewer != 'alice' [
105 │ err 'example22: web loopback failed'
106 │ ]
107 │ println (str/join ['web=' (mold dec_resp.status) '|id=' resp_json.id '|viewer=' resp_json.viewer] '')
108 │
109 │ // 4. Live loopback RFC 6455 WebSocket upgrade + masked frame echo
110 │ sln = net/listen-tcp .ip '127.0.0.1:0'
111 │ sport = str/to-i64 (str/split (net/addr sln) ':')[1]
112 │
113 │ ws_srv = spawn [
114 │ sock = net/accept sln
115 │ defer [ _ = net/close/or sock [.ok] ]
116 │ mut st = inet/tcp-stream (as-i64 sock) 'ws-client'
117 │ _ = ws/server-handshake mut st
118 │ f = ws/read-frame mut st
119 │ reply_txt = str/join ['echo:' (bytes/to-str f.payload)] ''
120 │ _ = ws/write-frame mut st (ws/Frame { opcode = ws/OP-TEXT, masked = false, payload = (bytes/from-str reply_txt) })
121 │ reply_txt
122 │ ]
123 │
124 │ mut wsc = inet/dial-tcp '127.0.0.1' sport
125 │ _ = ws/client-handshake mut wsc '127.0.0.1' '/chat'
126 │ _ = ws/write-frame mut wsc (ws/Frame { opcode = ws/OP-TEXT, masked = true, payload = (bytes/from-str 'hello-ws') })
127 │ echo_f = ws/read-frame mut wsc
128 │ _ = io/close mut wsc
129 │ _ = task/await ws_srv
130 │ _ = net/close sln
131 │
132 │ echo_txt = bytes/to-str echo_f.payload
133 │ if echo_txt != 'echo:hello-ws' [
134 │ err 'example22: websocket echo failed'
135 │ ]
136 │ println (str/join ['websocket=' echo_txt] '')