Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and th

**Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md).

**WebSocket auth (breaking vs early gateway builds):** browsers cannot send `Authorization` on WebSocket; use subprotocol `bearer.<pairing-token>` when opening `/ws` (see `web/js/app.js`).
**WebSocket authentication.** Pair with the gateway before opening `/ws`. For a browser client, offer both `ws` and `bearer.<pairing-token>` as subprotocols. The gateway selects `ws` and reads the token from the other entry. For a native client, offer `ws` and send the token in `Authorization: Bearer <pairing-token>`.

**Debug (macOS):** Symbols in `tests-dSYM/`. Use `lldb build/test_agent` then `settings set target.debug-file-search-path tests-dSYM`. Old `.dSYM` in repo root? Run `make clean-root-dsym`.

Expand Down
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Convention: one primary `.c` + `.h` per module; new tools go in `src/tools/<name

- Binds `[gateway] host` / `port` (default `127.0.0.1:18789`).
- **Auth:** pairing token; `/api/*` requires Bearer except `/health`, `/pair`, `/.well-known/*`.
- **WebSocket:** browsers use subprotocol `bearer.<token>` (not `Authorization` header).
- **WebSocket.** The gateway selects the `ws` subprotocol and validates the pairing token before the connection opens. See [WebSocket authentication](../README.md) for the browser and native client contracts.
- **Hardware API:** `/api/hardware/*` — board info, GPIO snapshot, tegrastats on Jetson; sensor/camera panels stubbed “Coming in v1.2”.
- **Rate limits:** per-IP on `/asap`; per-token on camera snapshot (1/sec) when enabled.
- **Signed manifest:** `GET /.well-known/asap/manifest.json` builds and signs the JSON synchronously in the HTTP handler (single-threaded today; not safe for concurrent manifest builds without locking).
Expand Down
2 changes: 1 addition & 1 deletion docs/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ This section summarizes Jetson Orin Nano Super / JetPack 6.2.x concerns that do
|------|------------------|----------------------------|
| Sandbox isolation | [`src/sandbox/sandbox.c`](../src/sandbox/sandbox.c), [`src/sandbox/sandbox_landlock.c`](../src/sandbox/sandbox_landlock.c) | user ns + `unshare` + PID-1 fork, Landlock workspace bound, cgroups v2, fail-closed isolation |
| Command policy | [`src/sandbox/allowlist.c`](../src/sandbox/allowlist.c) | Blocklist (incl. Jetson GPU + Argus), workspace path containment (DiD) |
| Gateway auth | [`src/gateway/http_lws.c`](../src/gateway/http_lws.c) | `requires_auth()` Bearer gate for `/api/*` |
| Gateway auth | [`src/gateway/http_lws.c`](../src/gateway/http_lws.c) | The gateway validates the bearer token for `/api/*` and during the WebSocket handshake. |
| Hardware HTTP API | [`src/gateway/routes_hardware.c`](../src/gateway/routes_hardware.c) | Read-only GET handlers, camera POST deferred stub |
| Rate limits | [`src/gateway/rate_limit.c`](../src/gateway/rate_limit.c) | Per-IP `/asap` RPM (64-slot table); reuses expired windows; **fail-closed** (429) when table is full and no slot expired |
| Camera spawn | [`src/hardware/hardware_camera.c`](../src/hardware/hardware_camera.c) | argv-only `execvp`, validated resolution/type/path |
Expand Down
72 changes: 31 additions & 41 deletions src/gateway/http_lws.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

static void http_lws_tx_completed(struct lws *wsi)
{
Expand Down Expand Up @@ -129,41 +130,32 @@ const char *http_request_bearer_token(struct lws *wsi, char *buf, size_t buf_siz
return buf + 7;
}

/** WebSocket upgrade: Bearer from Authorization (or custom header); browser may send bearer.<token> subprotocol. */
static int ws_copy_upgrade_token(struct lws *wsi, char *token_out, size_t token_size)
/* Browsers offer ws for negotiation and bearer.<token> for authentication. */
static const char *ws_subprotocol_token(char *list)
{
char auth_buf[256];
const char *token;
if (!wsi || !token_out || token_size == 0) return -1;
token_out[0] = '\0';
token = http_request_bearer_token(wsi, auth_buf, sizeof(auth_buf));
if (!token) {
int n = lws_hdr_custom_copy(wsi, auth_buf, sizeof(auth_buf), "authorization", 13);
if (n > 7 && strncmp(auth_buf, "Bearer ", 7) == 0)
token = auth_buf + 7;
char *next = NULL;
for (char *entry = strtok_r(list, ",", &next); entry;
entry = strtok_r(NULL, ",", &next)) {
entry += strspn(entry, " \t");
char *end = entry + strlen(entry);
while (end > entry && (end[-1] == ' ' || end[-1] == '\t'))
end--;
*end = '\0';
if (end - entry > 7 && strncmp(entry, "bearer.", 7) == 0)
return entry + 7;
}
if (token && token[0] != '\0') {
size_t len = strlen(token);
if (len >= token_size) len = token_size - 1;
memcpy(token_out, token, len);
token_out[len] = '\0';
return NULL;
}

static int ws_upgrade_allowed(const http_server_ctx_t *ctx, struct lws *wsi)
{
char header[512];
if (!ctx || !ctx->auth)
return 0;
}
{
char proto[512];
int n = lws_hdr_copy(wsi, proto, sizeof(proto), WSI_TOKEN_COLON_PROTOCOL);
if (n <= 0)
n = lws_hdr_custom_copy(wsi, proto, sizeof(proto), "sec-websocket-protocol", 22);
if (n > 7 && strncmp(proto, "bearer.", 7) == 0) {
const char *sub = proto + 7;
size_t len = (size_t)(n - 7);
if (len >= token_size) len = token_size - 1;
memcpy(token_out, sub, len);
token_out[len] = '\0';
return token_out[0] != '\0' ? 0 : -1;
}
}
return -1;
const char *token = http_request_bearer_token(wsi, header, sizeof(header));
if (!token && lws_hdr_copy(wsi, header, sizeof(header), WSI_TOKEN_PROTOCOL) > 0)
token = ws_subprotocol_token(header);
return token && auth_validate_token(ctx->auth, token);
}

static int is_static_path(const char *uri, int uri_len, int method)
Expand All @@ -190,6 +182,10 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user,
{
http_server_ctx_t *ctx = http_ctx_get();
(void)user;
/* libwebsockets calls the HTTP protocol before it selects ws. */
if (reason == LWS_CALLBACK_HTTP_CONFIRM_UPGRADE && in &&
strcasecmp(in, "websocket") == 0)
return ws_upgrade_allowed(ctx, wsi) ? 0 : -1;
if (!ctx) return 0;
switch (reason) {
case LWS_CALLBACK_HTTP: {
Expand Down Expand Up @@ -437,15 +433,9 @@ int ws_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user,
http_server_ctx_t *ctx = http_ctx_get();
(void)user;
switch (reason) {
case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE: {
char token_buf[256] = {0};
if (!ctx || !ctx->auth) return -1;
if (ws_copy_upgrade_token(wsi, token_buf, sizeof(token_buf)) != 0)
return -1;
if (!auth_validate_token(ctx->auth, token_buf))
return -1;
return 0;
}
case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE:
case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
return ws_upgrade_allowed(ctx, wsi) ? 0 : -1;
case LWS_CALLBACK_ESTABLISHED: {
int conn_id = ws_next_conn_id();
lws_set_wsi_user(wsi, (void *)(intptr_t)conn_id);
Expand Down
25 changes: 23 additions & 2 deletions src/gateway/ws.c
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ typedef struct ws_msg {
typedef struct {
ws_conn_t wsi;
int conn_id;
int replies_only;
} ws_conn_entry_t;

static ws_conn_entry_t g_conns[MAX_CONNECTIONS];
Expand Down Expand Up @@ -132,14 +133,15 @@ int ws_next_conn_id(void)
return atomic_fetch_add(&g_next_conn_id, 1) + 1;
}

int ws_register_conn(int conn_id, ws_conn_t wsi)
static int ws_register_conn_with_mode(int conn_id, ws_conn_t wsi, int replies_only)
{
int registered = 0;
pthread_mutex_lock(&g_mutex);
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (g_conns[i].wsi == NULL) {
g_conns[i].wsi = wsi;
g_conns[i].conn_id = conn_id;
g_conns[i].replies_only = replies_only;
registered = 1;
break;
}
Expand All @@ -148,6 +150,25 @@ int ws_register_conn(int conn_id, ws_conn_t wsi)
return registered ? 0 : -1;
}

#ifdef SHELLCLAW_WS_TEST
int ws_test_register_reply_conn(int conn_id, ws_conn_t wsi)
{
return ws_register_conn_with_mode(conn_id, wsi, 1);
}
#endif

int ws_register_conn(int conn_id, ws_conn_t wsi)
{
int replies_only = 0;
#ifndef SHELLCLAW_WS_TEST
/* libwebsockets keeps the request headers during the established callback. */
char value[16];
const char *view = lws_get_urlarg_by_name(wsi, "view=", value, sizeof(value));
replies_only = view && strcmp(view, "chat") == 0;
#endif
return ws_register_conn_with_mode(conn_id, wsi, replies_only);
}

static void ws_free_outgoing(ws_msg_t *m)
{
if (!m)
Expand Down Expand Up @@ -398,7 +419,7 @@ void ws_broadcast_text(const char *text)
pthread_mutex_lock(&g_mutex);
for (i = 0; i < MAX_CONNECTIONS; i++) {
ws_msg_t *m;
if (!g_conns[i].wsi)
if (!g_conns[i].wsi || g_conns[i].replies_only)
continue;
if (g_outgoing_count >= MAX_QUEUE)
break;
Expand Down
4 changes: 2 additions & 2 deletions src/gateway/ws.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ static inline int ws_text_payload_fits(size_t len_out)
typedef void *ws_conn_t;

/**
* Register a WebSocket connection. Called when connection is established.
* Register a WebSocket connection during the libwebsockets established callback.
*
* @param conn_id Unique connection ID (e.g. incrementing integer).
* @param wsi libwebsockets wsi (stored as ws_conn_t).
Expand Down Expand Up @@ -83,7 +83,7 @@ int ws_pop_incoming(char *session_id_out, size_t session_size,
*/
int ws_send_to(const char *session_id, const char *text);

/** Queue @p text for every connected WebSocket client. */
/** Queue @p text for open WebSockets that receive broadcast events. */
void ws_broadcast_text(const char *text);

/**
Expand Down
33 changes: 33 additions & 0 deletions tests/test_web_dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
*/
'use strict';

const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const dash = require('../web/js/dashboardView.js');
const hw = require('../web/js/hardwareView.js');
const escapeHtml = dash.escapeHtml;
Expand All @@ -19,6 +22,36 @@ function assert(cond, msg) {
}
}

function testPairedChatDisplaysRepliesAsText() {
let connection;
const location = { protocol: 'https:', host: 'localhost', hash: '#/chat' };
const log = { textContent: '' };
const elements = { app: {}, 'chat-log': log, 'chat-input': {} };
const token = '1234567890abcdef1234567890abcdef';
const script = fs.readFileSync(path.join(__dirname, '../web/js/app.js'), 'utf8');
vm.runInNewContext(script, {
location,
window: { location, addEventListener() {} },
document: { getElementById: id => elements[id], querySelectorAll: () => [] },
localStorage: { getItem: key => key === 'shellclaw_token' ? token : null },
WebSocket: function (url, protocols) {
this.url = url;
this.protocols = protocols;
connection = this;
},
});
const replies = ['The card is blue.', '{"type":"provider_status","providers":[]}',
'"Café" <strong>azul</strong>'];
replies.forEach(text => connection.onmessage({ data: text }));
assert(log.textContent === replies.join('\n') + '\n', 'chat displays each reply as text');
assert(log.innerHTML === undefined, 'chat does not insert reply markup');
assert(connection.url === 'wss://localhost/ws?view=chat', 'chat requests the replies-only socket');
assert(connection.protocols.length === 2 && connection.protocols[0] === 'ws' &&
connection.protocols[1] === 'bearer.' + token, 'paired chat offers both WebSocket protocols');
}

testPairedChatDisplaysRepliesAsText();

assert(escapeHtml(null) === '', 'null');
assert(escapeHtml(undefined) === '', 'undefined');
assert(escapeHtml('<script>alert(1)</script>').indexOf('<script>') === -1, 'script tag');
Expand Down
29 changes: 29 additions & 0 deletions tests/test_ws.c
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,34 @@ static int test_pop_incoming_invalid_args(void)
extern int ws_test_writable_count(void);
extern int ws_test_cancel_count(void);
extern void ws_test_reset_wake_counts(void);
extern int ws_test_register_reply_conn(int conn_id, ws_conn_t wsi);

static int test_chat_sockets_receive_only_direct_replies(void)
{
const char event[] = "{\"type\":\"provider_status\",\"providers\":[]}";
char buf[sizeof(event)];
size_t len;

ws_cleanup();
ASSERT(ws_test_register_reply_conn(1, (ws_conn_t)(intptr_t)1) == 0);
ASSERT(ws_register_conn(2, (ws_conn_t)(intptr_t)2) == 0);
ws_broadcast_text(event);
ASSERT(!ws_has_pending_outgoing(1));
ASSERT(ws_dequeue_outgoing(2, buf, sizeof(buf), &len) == 1);
ASSERT(len == strlen(event) && strcmp(buf, event) == 0);

ASSERT(ws_send_to("webchat:1", event) == 0);
ASSERT(ws_dequeue_outgoing(1, buf, sizeof(buf), &len) == 1);
ASSERT(len == strlen(event) && strcmp(buf, event) == 0);
ASSERT(!ws_has_pending_outgoing(2));

ws_unregister_conn(1);
ASSERT(ws_register_conn(3, (ws_conn_t)(intptr_t)3) == 0);
ws_broadcast_text(event);
ASSERT(ws_has_pending_outgoing(3));
ws_cleanup();
return 0;
}

/**
* Agent replies run on the main thread while lws_service runs on the gateway
Expand Down Expand Up @@ -408,6 +436,7 @@ int main(void)
RUN(test_send_to_rejects_bad_session());
RUN(test_dequeue_outgoing_and_pending());
RUN(test_broadcast_enqueues_per_conn());
RUN(test_chat_sockets_receive_only_direct_replies());
RUN(test_push_incoming_rejects_empty());
RUN(test_pop_incoming_invalid_args());
RUN(test_shutdown_stops_pop());
Expand Down
18 changes: 11 additions & 7 deletions web/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,17 @@
});
}

function wsConnect(onMessage) {
function wsConnect(onMessage, repliesOnly = false) {
const token = getToken();
if (!token) return null;
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
/* Browsers cannot set Authorization on WebSocket; server accepts bearer.<token> subprotocol. */
const ws = new WebSocket(proto + '//' + location.host + '/ws', ['bearer.' + token]);
ws.onmessage = e => { try { const d = JSON.parse(e.data); onMessage(d); } catch (_) {} };
const path = repliesOnly ? '/ws?view=chat' : '/ws';
const ws = new WebSocket(proto + '//' + location.host + path, ['ws', 'bearer.' + token]);
if (repliesOnly) {
ws.onmessage = e => onMessage(e.data);
} else {
ws.onmessage = e => { try { const d = JSON.parse(e.data); onMessage(d); } catch (_) {} };
}
return ws;
}

Expand Down Expand Up @@ -134,10 +138,10 @@
render(app, '<h1>Chat</h1><div id="chat-log"></div><input id="chat-input" placeholder="Type message...">');
const log = document.getElementById('chat-log');
const input = document.getElementById('chat-input');
const ws = wsConnect(function (msg) {
if (msg.type === 'message') log.textContent += (msg.text || '') + '\n';
const ws = wsConnect(function (text) {
log.textContent += text + '\n';
log.scrollTop = log.scrollHeight;
});
}, true);
if (!ws) { log.textContent = 'Not authenticated. Go to pairing.'; return; }
input.onkeydown = function (e) {
if (e.key !== 'Enter') return;
Expand Down
Loading