GraphQL, WebSocket, import, runner and CLI (M5, M6) plus packaging

- GraphQL editor with schema introspection, cached schema,
  autocomplete and explorer
- WebSocket: auth and subprotocols in the handshake, text/JSON/hex/file
  messages, saved messages, live log with filter, search and export,
  reconnect with backoff
- Import from Postman (collections and environments), Bruno, Insomnia,
  OpenAPI/Swagger and cURL; imported scripts are kept as docs, never run;
  credentials move to the gitignored secrets file
- Code snippets for cURL, fetch, Python, HTTPie, Go, PowerShell;
  Postman export
- Runner for folders and collections with JSON and JUnit reports
- knock CLI: send, run, import, auth login/debug/logout
- Large JSON responses parsed off the main thread
- PKGBUILDs, desktop entry with knock:// handler, CI workflow, README
This commit is contained in:
2026-11-27 17:13:06 +01:00
parent a469697af7
commit fc253126a7
51 changed files with 8437 additions and 24 deletions
+176
View File
@@ -621,3 +621,179 @@ pub fn path_params(url: String) -> Vec<String> {
pub fn app_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[tauri::command]
pub fn write_text_file(path: String, text: String) -> Res<()> {
std::fs::write(&path, text).map_err(err)
}
#[derive(Serialize)]
pub struct RunResult {
pub report: knock_core::runner::RunReport,
pub json: String,
pub junit: String,
}
#[tauri::command]
pub async fn runner_run(
app: AppHandle,
col: String,
folder: String,
env: Option<String>,
bail: bool,
delay_ms: u64,
) -> Res<RunResult> {
use tauri::Emitter;
let state = app.state::<AppState>();
let c = state.collection(&col).map_err(errx)?;
let file = env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default();
let secrets = Arc::new(SecretStore::new(&c.manifest.id, env.as_deref(), file.vars, true));
let oauth = Arc::new(crate::oauth::TokenLookup::new(&app, &c, env.as_deref()));
let host = crate::oauth::Host::new(app.clone(), Some(col.clone()), env.clone());
let engine = state.engine.clone();
let opts = knock_core::runner::RunOptions {
env: env.clone(),
bail,
delay_ms,
globals: db::globals_load(&state.db.lock().unwrap()).unwrap_or_default(),
runtime: state.runtime_vars(&col),
};
let deps = knock_core::runner::RunDeps { engine: &engine, secrets, oauth: Some(oauth), host: Some(&host) };
let report = knock_core::runner::run(&c, &folder, &opts, &deps, |done, total, item| {
let _ = app.emit("run-progress", (done, total, item));
})
.await;
for (k, v) in &report.runtime {
state.set_runtime(&col, k, Some(v.clone()), false);
}
let json = state.engine.save_jar(&col);
let _ = db::jar_save(&state.db.lock().unwrap(), &col, &json);
Ok(RunResult { json: knock_core::runner::to_json(&report), junit: knock_core::runner::to_junit(&report), report })
}
// ---------------------------------------------------------------- import / export
use knock_core::import::{self as importer, ImportReport, Kind as ImportKind};
#[tauri::command]
pub fn import_curl(text: String) -> Res<Request> {
importer::parse_curl(&text).map_err(errx)
}
#[tauri::command]
pub fn import_detect(text: String) -> Option<ImportKind> {
importer::detect(&text)
}
/// Imports a file or folder (Bruno) into a new collection at `dest` and opens it.
#[tauri::command]
pub fn import_source(app: AppHandle, state: State<'_, AppState>, source: String, dest: String) -> Res<(ImportReport, CollectionView)> {
let src = PathBuf::from(&source);
let dest_path = PathBuf::from(&dest);
let report = if src.is_dir() {
if !src.join("bruno.json").exists() {
return Err("this folder is not a Bruno collection (no bruno.json)".into());
}
importer::import_bruno(&src, &dest_path).map_err(errx)?
} else {
let text = std::fs::read_to_string(&src).map_err(|e| format!("{source}: {e}"))?;
import_text_into(&text, &dest_path)?
};
let c = Collection::open(&report.collection_root).map_err(errx)?;
let view = register(&app, &state, c)?;
Ok((report, view))
}
#[tauri::command]
pub fn import_text(app: AppHandle, state: State<'_, AppState>, text: String, dest: String) -> Res<(ImportReport, CollectionView)> {
let report = import_text_into(&text, &PathBuf::from(&dest))?;
let c = Collection::open(&report.collection_root).map_err(errx)?;
let view = register(&app, &state, c)?;
Ok((report, view))
}
fn import_text_into(text: &str, dest: &std::path::Path) -> Res<ImportReport> {
match importer::detect(text) {
Some(ImportKind::PostmanCollection) => importer::import_postman(text, dest).map_err(errx),
Some(ImportKind::Insomnia) => importer::import_insomnia(text, dest).map_err(errx),
Some(ImportKind::Openapi) => importer::import_openapi(text, dest).map_err(errx),
Some(ImportKind::Curl) => {
let mut req = importer::parse_curl(text).map_err(errx)?;
let name = dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "Imported".into());
let c = Collection::create(dest, &name).map_err(errx)?;
// Credentials from the command go to the gitignored secrets file, not the request.
let mut store = IndexMap::new();
importer::externalize_secrets(&mut req.auth, "curl", &mut store);
if !store.is_empty() {
let mut f = c.secrets_file("local").unwrap_or_default();
f.vars.extend(store);
c.save_secrets_file("local", &f).map_err(errx)?;
}
c.create_request("", &req).map_err(errx)?;
Ok(ImportReport { collection_root: c.root.clone(), requests: 1, ..Default::default() })
}
Some(ImportKind::PostmanEnvironment) => Err("this is a Postman environment. Open the collection first, then import the environment from its Environments tab".into()),
None => Err("could not recognise the format. knock imports Postman, Bruno, Insomnia, OpenAPI/Swagger and cURL".into()),
}
}
#[tauri::command]
pub fn import_environment(state: State<'_, AppState>, col: String, source: String) -> Res<CollectionView> {
let text = std::fs::read_to_string(&source).map_err(|e| format!("{source}: {e}"))?;
let root = state.with_collection(&col, |c| Ok(c.root.clone())).map_err(errx)?;
importer::import_postman_environment(&text, &root).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn export_postman(state: State<'_, AppState>, col: String, path: String) -> Res<()> {
let json = state.with_collection(&col, knock_core::export::export_postman).map_err(errx)?;
std::fs::write(&path, json).map_err(err)
}
/// Code for the request. `resolve` fills in variables (secrets stay masked);
/// otherwise `{{placeholders}}` are kept as written.
#[tauri::command]
pub async fn code_snippet(app: AppHandle, args: ScopeArgs, lang: knock_core::export::Lang, resolve: bool) -> Res<String> {
use knock_core::prepare::{Prepared, PreparedBody};
let state = app.state::<AppState>();
let p = if resolve {
let ctx = build_context(&app, &state, &args).map_err(errx)?;
let mut p = knock_core::prepare::prepare(&args.request, &ctx).map_err(errx)?;
// Stored tokens only; generating code never starts a login.
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await;
let mask = |s: &str| ctx.resolver.mask(s);
p.url = mask(&p.url);
p.headers = p.headers.into_iter().map(|(k, v)| (k, mask(&v))).collect();
if let PreparedBody::Bytes { data, preview } = &p.body {
let text = mask(&String::from_utf8_lossy(data));
p.body = PreparedBody::Bytes { data: text.clone().into_bytes(), preview: preview.clone() };
}
p
} else {
let r = &args.request;
let body = match r.body.kind {
BodyType::None => PreparedBody::None,
BodyType::FormUrlencoded => {
let s = r.body.form.iter().filter(|f| f.enabled).map(|f| format!("{}={}", f.name, f.value)).collect::<Vec<_>>().join("&");
PreparedBody::Bytes { preview: s.clone(), data: s.into_bytes() }
}
_ => PreparedBody::Bytes { preview: r.body.content.clone(), data: r.body.content.clone().into_bytes() },
};
let mut headers: Vec<(String, String)> = r.headers.iter().filter(|h| h.enabled).map(|h| (h.name.clone(), h.value.clone())).collect();
if r.body.kind == BodyType::Json && !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) {
headers.push(("Content-Type".into(), "application/json".into()));
}
Prepared {
method: r.method().to_string(),
url: r.url.clone(),
headers,
body,
settings: r.settings.clone(),
missing: vec![],
cycles: vec![],
}
};
Ok(knock_core::export::snippet(&p, lang))
}
+15
View File
@@ -3,6 +3,7 @@ mod db;
mod oauth;
mod state;
mod watch;
mod ws;
use tauri::Manager;
@@ -22,6 +23,7 @@ pub fn run() {
let dir = app.path().app_data_dir()?;
app.manage(state::AppState::new(dir)?);
app.manage(oauth::OauthState::default());
app.manage(ws::WsState::default());
Ok(())
})
.invoke_handler(tauri::generate_handler![
@@ -67,11 +69,24 @@ pub fn run() {
commands::setting_set,
commands::path_params,
commands::app_version,
commands::write_text_file,
commands::runner_run,
commands::import_curl,
commands::import_detect,
commands::import_source,
commands::import_text,
commands::import_environment,
commands::export_postman,
commands::code_snippet,
oauth::oauth_status,
oauth::oauth_run,
oauth::oauth_callback,
oauth::oauth_deep_link,
oauth::oauth_cancel,
ws::ws_connect,
ws::ws_send,
ws::ws_ping,
ws::ws_close,
])
.run(tauri::generate_context!())
.expect("error while running knock");
+209
View File
@@ -0,0 +1,209 @@
//! WebSocket sessions, one per tab. Frames are pushed to the UI as events.
use crate::commands::{build_context, ScopeArgs};
use crate::state::AppState;
use futures_util::{SinkExt, StreamExt};
use knock_core::model::WsFormat;
use knock_core::prepare::prepare;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::{Bytes, Message};
#[derive(Default)]
pub struct WsState {
sessions: Mutex<HashMap<String, mpsc::UnboundedSender<Cmd>>>,
}
enum Cmd {
Send(Message),
Close,
}
#[derive(Clone, Serialize)]
struct WsEvent {
tab: String,
at: i64,
/// open, text, binary, ping, pong, close, error, status
kind: &'static str,
/// in, out, sys
dir: &'static str,
data: String,
size: usize,
}
fn emit(app: &AppHandle, tab: &str, kind: &'static str, dir: &'static str, data: String, size: usize) {
let _ = app.emit(
"ws-event",
WsEvent { tab: tab.into(), at: chrono::Utc::now().timestamp_millis(), kind, dir, data, size },
);
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect::<Vec<_>>().join(" ")
}
#[derive(Deserialize)]
pub struct WsArgs {
#[serde(flatten)]
pub scope: ScopeArgs,
pub tab: String,
}
#[tauri::command]
pub async fn ws_connect(app: AppHandle, args: WsArgs) -> Result<(), String> {
ws_close(app.clone(), args.tab.clone());
let (tx, rx) = mpsc::unbounded_channel();
app.state::<WsState>().sessions.lock().unwrap().insert(args.tab.clone(), tx);
let reconnect = args.scope.request.ws.as_ref().is_some_and(|w| w.auto_reconnect);
tauri::async_runtime::spawn(run(app, args, rx, reconnect));
Ok(())
}
async fn run(app: AppHandle, args: WsArgs, mut rx: mpsc::UnboundedReceiver<Cmd>, reconnect: bool) {
let tab = args.tab.clone();
let mut attempt = 0u32;
loop {
match session(&app, &args, &mut rx).await {
Ok(true) => return, // closed by the user
Ok(false) => emit(&app, &tab, "close", "sys", "connection closed by the server".into(), 0),
Err(e) => emit(&app, &tab, "error", "sys", e, 0),
}
let still_open = app.state::<WsState>().sessions.lock().unwrap().contains_key(&tab);
if !reconnect || !still_open {
app.state::<WsState>().sessions.lock().unwrap().remove(&tab);
emit(&app, &tab, "status", "sys", "disconnected".into(), 0);
return;
}
attempt += 1;
let wait = Duration::from_secs((1u64 << attempt.min(5)).min(30));
emit(&app, &tab, "status", "sys", format!("reconnecting in {} s (attempt {attempt})", wait.as_secs()), 0);
tokio::select! {
_ = tokio::time::sleep(wait) => {}
cmd = rx.recv() => {
if matches!(cmd, None | Some(Cmd::Close)) {
emit(&app, &tab, "status", "sys", "disconnected".into(), 0);
return;
}
}
}
}
}
/// Ok(true) when the user closed it, Ok(false) when the server did.
async fn session(app: &AppHandle, args: &WsArgs, rx: &mut mpsc::UnboundedReceiver<Cmd>) -> Result<bool, String> {
let tab = &args.tab;
let state = app.state::<AppState>();
let ctx = build_context(app, &state, &args.scope).map_err(|e| format!("{e:#}"))?;
let mut p = prepare(&args.scope.request, &ctx).map_err(|e| format!("{e:#}"))?;
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await;
if auth.failed() {
let _ = app.emit("ws-auth", (tab.clone(), &auth));
return Err("authentication failed, see the Auth tab".into());
}
let protocols = args.scope.request.ws.as_ref().map(|w| w.subprotocols.clone()).unwrap_or_default();
emit(app, tab, "status", "sys", format!("connecting to {}", p.url), 0);
let (sock, hs) = knock_core::ws::connect(&p, &protocols).await.map_err(|e| format!("{e:#}"))?;
let _ = app.emit("ws-handshake", (tab.clone(), &hs, &auth));
emit(app, tab, "open", "sys", format!("connected in {:.0} ms{}", hs.ms, hs.protocol.as_ref().map(|p| format!(", protocol {p}")).unwrap_or_default()), 0);
let (mut write, mut read) = sock.split();
loop {
tokio::select! {
cmd = rx.recv() => match cmd {
Some(Cmd::Send(m)) => {
let (kind, data, size) = describe(&m);
if let Err(e) = write.send(m).await {
return Err(format!("send failed: {e}"));
}
emit(app, tab, kind, "out", data, size);
}
Some(Cmd::Close) | None => {
let _ = write.send(Message::Close(None)).await;
emit(app, tab, "close", "sys", "closed".into(), 0);
return Ok(true);
}
},
msg = read.next() => match msg {
Some(Ok(Message::Close(frame))) => {
let why = frame.map(|f| format!("code {} {}", u16::from(f.code), f.reason)).unwrap_or_default();
emit(app, tab, "close", "in", why, 0);
return Ok(false);
}
Some(Ok(m)) => {
let (kind, data, size) = describe(&m);
emit(app, tab, kind, "in", data, size);
}
Some(Err(e)) => return Err(e.to_string()),
None => return Ok(false),
}
}
}
}
fn describe(m: &Message) -> (&'static str, String, usize) {
match m {
Message::Text(t) => ("text", t.to_string(), t.len()),
Message::Binary(b) => ("binary", hex(b), b.len()),
Message::Ping(b) => ("ping", hex(b), b.len()),
Message::Pong(b) => ("pong", hex(b), b.len()),
Message::Close(_) => ("close", String::new(), 0),
Message::Frame(_) => ("binary", String::new(), 0),
}
}
#[tauri::command]
pub fn ws_send(
app: AppHandle,
tab: String,
format: WsFormat,
content: String,
file: Option<String>,
scope: Option<ScopeArgs>,
) -> Result<(), String> {
// Messages may use {{variables}} like any other field.
let content = match &scope {
Some(s) => {
let state = app.state::<AppState>();
let ctx = build_context(&app, &state, s).map_err(|e| format!("{e:#}"))?;
let text = ctx.resolver.apply(&content);
if format == WsFormat::Json {
knock_core::prepare::strip_json_comments(&text)
} else {
text
}
}
None => content,
};
let msg = if let Some(f) = file {
Message::Binary(Bytes::from(std::fs::read(&f).map_err(|e| format!("{f}: {e}"))?))
} else {
match format {
WsFormat::Hex => Message::Binary(Bytes::from(knock_core::ws::parse_hex(&content).map_err(|e| e.to_string())?)),
_ => Message::Text(content.into()),
}
};
let state = app.state::<WsState>();
let sessions = state.sessions.lock().unwrap();
let tx = sessions.get(&tab).ok_or("not connected")?;
tx.send(Cmd::Send(msg)).map_err(|_| "not connected".to_string())
}
#[tauri::command]
pub fn ws_ping(app: AppHandle, tab: String) -> Result<(), String> {
let state = app.state::<WsState>();
let sessions = state.sessions.lock().unwrap();
let tx = sessions.get(&tab).ok_or("not connected")?;
tx.send(Cmd::Send(Message::Ping(Bytes::from_static(b"knock")))).map_err(|_| "not connected".to_string())
}
#[tauri::command]
pub fn ws_close(app: AppHandle, tab: String) {
if let Some(tx) = app.state::<WsState>().sessions.lock().unwrap().remove(&tab) {
let _ = tx.send(Cmd::Close);
}
}