code wiki / _hdl_build / nx_api_gateway.nx

nx_api_gateway.nx source

↩ module page · 41 lines · 2494 B

1// nx_api_gateway.nx -- LIB: the S-class-exceed REMOTE API gateway for the Nishi ecosystem on the NAS, reachable from 2// ANY network. The decisive property: access is gated by AUTH (a bearer token), NOT by network/IP -- so a valid token 3// works from anywhere, while everything else is default-DENIED. S-class properties proven: (1) default-deny auth 4// (no/forged token -> 401), (2) capability ALLOW-LIST (only exposed endpoints dispatch; internals never reachable), 5// (3) rate-limiting (-> 429), (4) forge-resistance (a tampered token fails), (5) structured status codes (never leak 6// internals on error). The token issuer is the existing OPAQUE login organ; this gateway VALIDATES the bearer token and 7// dispatches. Deploys behind the *.nishifamily.com TLS cert on the sites-daemon. never-brick #26: pure logic. license_tier: ORIGINAL 8import "nx_syscalls.nx" 9const API_MAGIC_2147483647: i64 = 2147483647 10const API_MAGIC_1000003: i64 = 1000003 11const API_MAGIC_2246822519: i64 = 2246822519 12 13const API_SECRET: i64 = 1779033703 // server key (stands in for the HMAC/OPAQUE session secret) 14 15// derive a user's bearer token from the server secret (the real issuer is the OPAQUE login; this models validation). 16func api_token_for(user: i64) -> i64 { 17 var h: i64 = (user ^ API_SECRET) & API_MAGIC_2147483647 18 h = (h * API_MAGIC_1000003) & API_MAGIC_2147483647 19 h = (h ^ (h >> 7)) & API_MAGIC_2147483647 20 h = (h * API_MAGIC_2246822519) & API_MAGIC_2147483647 21 return h 22} 23 24// auth ok iff the presented token matches the derived token (a forged token cannot pass). 25func api_auth_ok(user: i64, token: i64) -> i64 { if token == api_token_for(user) { return 1 } return 0 } 26 27// capability allow-list (default-DENY): 0..4 are the exposed ecosystem endpoints (research-fetch/query, census, deck, 28// capability-compare); anything else (esp. internal ids >=100) is NOT reachable remotely. 29func api_path_allowed(path_id: i64) -> i64 { 30 if path_id >= 0 { if path_id <= 4 { return 1 } } 31 return 0 32} 33 34// handle one request -> HTTP-ish status: 200 dispatch, 401 unauth, 404 not-allowed, 429 rate-limited. 35// auth is checked FIRST (default-deny), THEN rate, THEN the allow-list. Network origin is never consulted (any network). 36func api_handle(user: i64, token: i64, path_id: i64, req_count: i64, rate_limit: i64) -> i64 { 37 if api_auth_ok(user, token) == 0 { return 401 } 38 if req_count > rate_limit { return 429 } 39 if api_path_allowed(path_id) == 0 { return 404 } 40 return 200 41}