code wiki / _hdl_build / nx_apistack_cors.nx
nx_apistack_cors.nx source
↩ module page · 44 lines · 2028 B
1// nx_apistack_cors.nx -- CAP-API-CORS: cross-origin control for /api. DENY-BY-DEFAULT: an Origin is allowed only if
2// it matches a row in the allowlist (cors_allow.conf, one origin per line); everything else gets no CORS headers.
3// Allowlist is DATA (add an origin = a row) -- the sovereign exceed over wildcard/reflected CORS. license_tier: ORIGINAL
4import "nx_syscalls.nx"
5import "nx_site_lock_lib.nx"
6const K_MAGIC_65536: i64 = 65536
7
8func cors_read_file(path: *u8, out: *u8, cap: i64) -> i64 {
9 let fd: i64 = sys_openat_rd(path); if fd < 0 { return 0 }
10 var total: i64 = 0; var go: i64 = 1
11 while go == 1 {
12 let tail: *u8 = (out as i64 + total) as *u8
13 let nr: i64 = sys_read(fd, tail, cap - total)
14 if nr <= 0 { go = 0 }
15 if nr > 0 { total = total + nr }
16 if total >= cap { go = 0 }
17 }
18 sys_close(fd); return total
19}
20// 1 iff `origin` exactly matches an allowlist row (deny-by-default). Empty origin -> 0.
21func cors_allowed(conf_path: *u8, origin: *u8, origin_n: i64) -> i64 {
22 if origin_n <= 0 { return 0 }
23 let buf: *u8 = sys_mmap(K_MAGIC_65536); let n: i64 = cors_read_file(conf_path, buf, K_MAGIC_65536)
24 var ls: i64 = 0
25 while ls < n {
26 var le: i64 = slk_line_end(buf, n, ls)
27 var e: i64 = le
28 if e > ls { if buf[e - 1] == (13 as u8) { e = e - 1 } } // trim a trailing CR
29 if e > ls { if buf[ls] != (35 as u8) {
30 if slk_eq(slk_at(buf, ls), e - ls, origin, origin_n) == 1 { return 1 }
31 } }
32 ls = le + 1
33 }
34 return 0
35}
36// emit the Access-Control-Allow-Origin header for an ALREADY-allowed origin. Returns length.
37func cors_emit_header(out: *u8, origin: *u8, origin_n: i64) -> i64 {
38 var o: i64 = 0
39 let h: *u8 = "Access-Control-Allow-Origin: " as *u8
40 var i: i64 = 0; while h[i] != (0 as u8) { out[o] = h[i]; o = o + 1; i = i + 1 }
41 i = 0; while i < origin_n { out[o] = origin[i]; o = o + 1; i = i + 1 }
42 out[o] = 13 as u8; o = o + 1; out[o] = 10 as u8; o = o + 1
43 return o
44}