mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 15:29:40 +01:00
Skeleton, REST core, variables and JSON editor (M0–M2)
- knock-core: YAML collection format with unknown-field round trip, variable resolution across scopes with secrets and dynamic values, HTTP engine with manual redirects, cookie jar and large-body spill, basic/bearer/API key auth with debug output, assertions and extracts - Tauri app: collection commands, file watcher, SQLite history, keyring-backed secrets - Svelte UI: sidebar tree, tabs, request editor, response viewer, JSON form/code editor with schema hints, environments, settings
This commit is contained in:
@@ -0,0 +1,623 @@
|
||||
use crate::db;
|
||||
use crate::state::AppState;
|
||||
use crate::watch;
|
||||
use indexmap::IndexMap;
|
||||
use knock_core::collection::{Collection, EnvEntry, FolderNode, Problem};
|
||||
use knock_core::model::*;
|
||||
use knock_core::prepare::{ContextInput, RequestContext};
|
||||
use knock_core::run::{execute, RunOutput};
|
||||
use knock_core::secrets::{self, SecretStore};
|
||||
use knock_core::vars::{VarInfo, DYNAMIC_VARS};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
|
||||
type Res<T> = Result<T, String>;
|
||||
|
||||
fn err(e: impl std::fmt::Display) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
fn errx(e: anyhow::Error) -> String {
|
||||
format!("{e:#}")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- collections
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct CollectionView {
|
||||
pub id: String,
|
||||
pub root: String,
|
||||
pub name: String,
|
||||
pub tree: FolderNode,
|
||||
pub environments: Vec<EnvEntry>,
|
||||
pub problems: Vec<Problem>,
|
||||
}
|
||||
|
||||
fn view(c: &Collection) -> CollectionView {
|
||||
CollectionView {
|
||||
id: c.manifest.id.clone(),
|
||||
root: c.root.display().to_string(),
|
||||
name: c.manifest.name.clone(),
|
||||
tree: c.tree.clone(),
|
||||
environments: c.environments.clone(),
|
||||
problems: c.problems.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_recent(state: &AppState, root: &str) {
|
||||
let db = state.db.lock().unwrap();
|
||||
let mut recent: Vec<String> = db::kv_get(&db, "recent")
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
recent.retain(|r| r != root);
|
||||
recent.insert(0, root.to_string());
|
||||
recent.truncate(12);
|
||||
let _ = db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap());
|
||||
}
|
||||
|
||||
fn register(app: &AppHandle, state: &AppState, c: Collection) -> Res<CollectionView> {
|
||||
let v = view(&c);
|
||||
if let Ok(Some(json)) = db::jar_load(&state.db.lock().unwrap(), &v.id) {
|
||||
state.engine.load_jar(&v.id, &json);
|
||||
}
|
||||
let root = c.root.clone();
|
||||
state.collections.write().unwrap().insert(v.id.clone(), c);
|
||||
remember_recent(state, &v.root);
|
||||
watch::start(app, state, &v.id, &root);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn collection_open(app: AppHandle, state: State<'_, AppState>, path: String) -> Res<CollectionView> {
|
||||
let c = Collection::open(&path).map_err(errx)?;
|
||||
register(&app, &state, c)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn collection_create(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
path: String,
|
||||
name: String,
|
||||
) -> Res<CollectionView> {
|
||||
let c = Collection::create(&path, &name).map_err(errx)?;
|
||||
register(&app, &state, c)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn collection_get(state: State<'_, AppState>, id: String) -> Res<CollectionView> {
|
||||
state.with_collection(&id, |c| Ok(view(c))).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn collection_close(state: State<'_, AppState>, id: String) -> Res<()> {
|
||||
state.collections.write().unwrap().remove(&id);
|
||||
state.watchers.lock().unwrap().remove(&id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn recent_collections(state: State<'_, AppState>) -> Res<Vec<String>> {
|
||||
let db = state.db.lock().unwrap();
|
||||
Ok(db::kv_get(&db, "recent")
|
||||
.map_err(errx)?
|
||||
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|p| PathBuf::from(p).join("knock.yaml").exists())
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn recent_forget(state: State<'_, AppState>, path: String) -> Res<()> {
|
||||
let db = state.db.lock().unwrap();
|
||||
let mut recent: Vec<String> = db::kv_get(&db, "recent")
|
||||
.map_err(errx)?
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
recent.retain(|r| r != &path);
|
||||
db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap()).map_err(errx)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tree edits
|
||||
|
||||
fn after_edit(state: &AppState, col: &str) -> Res<CollectionView> {
|
||||
state.reload(col).map_err(errx)?;
|
||||
state.with_collection(col, |c| Ok(view(c))).map_err(errx)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct EditResult {
|
||||
pub id: String,
|
||||
pub collection: CollectionView,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn request_get(state: State<'_, AppState>, col: String, id: String) -> Res<Request> {
|
||||
state.with_collection(&col, |c| c.request(&id)).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn request_save(state: State<'_, AppState>, col: String, id: String, request: Request) -> Res<CollectionView> {
|
||||
state.with_collection(&col, |c| c.save_request(&id, &request)).map_err(errx)?;
|
||||
after_edit(&state, &col)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn request_create(
|
||||
state: State<'_, AppState>,
|
||||
col: String,
|
||||
folder: String,
|
||||
request: Request,
|
||||
) -> Res<EditResult> {
|
||||
let id = state.with_collection(&col, |c| c.create_request(&folder, &request)).map_err(errx)?;
|
||||
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn folder_create(state: State<'_, AppState>, col: String, parent: String, name: String) -> Res<EditResult> {
|
||||
let id = state.with_collection(&col, |c| c.create_folder(&parent, &name)).map_err(errx)?;
|
||||
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn node_rename(state: State<'_, AppState>, col: String, id: String, name: String) -> Res<EditResult> {
|
||||
let id = state.with_collection(&col, |c| c.rename(&id, &name)).map_err(errx)?;
|
||||
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn node_duplicate(state: State<'_, AppState>, col: String, id: String) -> Res<EditResult> {
|
||||
let id = state.with_collection(&col, |c| c.duplicate(&id)).map_err(errx)?;
|
||||
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn node_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
|
||||
state.with_collection(&col, |c| c.delete(&id)).map_err(errx)?;
|
||||
after_edit(&state, &col)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn node_move(
|
||||
state: State<'_, AppState>,
|
||||
col: String,
|
||||
id: String,
|
||||
folder: String,
|
||||
index: Option<usize>,
|
||||
) -> Res<EditResult> {
|
||||
let id = state.with_collection(&col, |c| c.move_node(&id, &folder, index)).map_err(errx)?;
|
||||
Ok(EditResult { id, collection: after_edit(&state, &col)? })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn folder_get(state: State<'_, AppState>, col: String, id: String) -> Res<FolderMeta> {
|
||||
state.with_collection(&col, |c| c.folder_meta(&id)).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn folder_save(state: State<'_, AppState>, col: String, id: String, meta: FolderMeta) -> Res<CollectionView> {
|
||||
state.with_collection(&col, |c| c.save_folder_meta(&id, &meta)).map_err(errx)?;
|
||||
after_edit(&state, &col)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn manifest_get(state: State<'_, AppState>, col: String) -> Res<Manifest> {
|
||||
state.with_collection(&col, |c| Ok(c.manifest.clone())).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn manifest_save(state: State<'_, AppState>, col: String, manifest: Manifest) -> Res<CollectionView> {
|
||||
state.with_collection(&col, |c| c.save_manifest(&manifest)).map_err(errx)?;
|
||||
after_edit(&state, &col)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- environments
|
||||
|
||||
#[tauri::command]
|
||||
pub fn env_get(state: State<'_, AppState>, col: String, id: String) -> Res<Environment> {
|
||||
state.with_collection(&col, |c| c.environment(&id)).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn env_save(state: State<'_, AppState>, col: String, id: String, env: Environment) -> Res<CollectionView> {
|
||||
state.with_collection(&col, |c| c.save_environment(&id, &env)).map_err(errx)?;
|
||||
after_edit(&state, &col)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn env_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
|
||||
state.with_collection(&col, |c| c.delete_environment(&id)).map_err(errx)?;
|
||||
after_edit(&state, &col)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SecretStatus {
|
||||
pub name: String,
|
||||
pub source: Option<secrets::SecretSource>,
|
||||
pub value: Option<String>,
|
||||
}
|
||||
|
||||
/// Where each secret of an environment currently comes from. Values are
|
||||
/// returned so the UI can reveal them on demand; it masks by default.
|
||||
#[tauri::command]
|
||||
pub fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<Vec<SecretStatus>> {
|
||||
let (e, file) = state
|
||||
.with_collection(&col, |c| Ok((c.environment(&env)?, c.secrets_file(&env)?)))
|
||||
.map_err(errx)?;
|
||||
let store = SecretStore::new(&col, Some(&env), file.vars, true);
|
||||
Ok(e.vars
|
||||
.iter()
|
||||
.filter(|(_, v)| v.secret)
|
||||
.map(|(k, _)| {
|
||||
let found = store.find(k);
|
||||
SecretStatus {
|
||||
name: k.clone(),
|
||||
source: found.as_ref().map(|f| f.1),
|
||||
value: found.map(|f| f.0),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn secret_set(
|
||||
state: State<'_, AppState>,
|
||||
col: String,
|
||||
env: Option<String>,
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
target: String,
|
||||
) -> Res<()> {
|
||||
match target.as_str() {
|
||||
"file" => {
|
||||
let env = env.ok_or("secrets files belong to an environment")?;
|
||||
state
|
||||
.with_collection(&col, |c| {
|
||||
let mut f = c.secrets_file(&env)?;
|
||||
match &value {
|
||||
Some(v) => {
|
||||
f.vars.insert(name.clone(), v.clone());
|
||||
}
|
||||
None => {
|
||||
f.vars.shift_remove(&name);
|
||||
}
|
||||
}
|
||||
c.save_secrets_file(&env, &f)
|
||||
})
|
||||
.map_err(errx)
|
||||
}
|
||||
_ => match value {
|
||||
Some(v) => secrets::keyring_set(&col, env.as_deref(), &name, &v).map_err(|e| {
|
||||
format!("could not write to the system keyring ({e:#}). Is a Secret Service (KWallet, GNOME Keyring) running? You can store it in the secrets file instead.")
|
||||
}),
|
||||
None => secrets::keyring_delete(&col, env.as_deref(), &name).map_err(errx),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- variables
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ScopeArgs {
|
||||
pub col: Option<String>,
|
||||
pub request_id: Option<String>,
|
||||
pub request: Request,
|
||||
pub env: Option<String>,
|
||||
}
|
||||
|
||||
pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
|
||||
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
|
||||
match &a.col {
|
||||
Some(col) => {
|
||||
let c = state.collection(col)?;
|
||||
let file = a.env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default();
|
||||
let store = SecretStore::new(&c.manifest.id, a.env.as_deref(), file.vars, true);
|
||||
let rid = a.request_id.clone().unwrap_or_else(|| "__unsaved__.yaml".into());
|
||||
RequestContext::build(ContextInput {
|
||||
collection: &c,
|
||||
request_id: &rid,
|
||||
request: &a.request,
|
||||
env: a.env.as_deref(),
|
||||
runtime: state.runtime_vars(col),
|
||||
globals,
|
||||
secrets: Arc::new(store),
|
||||
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(state, &c, a.env.as_deref()))),
|
||||
})
|
||||
}
|
||||
None => {
|
||||
let mut ctx = RequestContext::standalone(&a.request, std::env::temp_dir());
|
||||
ctx.resolver.layers.push(knock_core::vars::Layer::new(
|
||||
knock_core::vars::Scope::Global,
|
||||
"global",
|
||||
globals,
|
||||
));
|
||||
ctx.resolver.push_front(knock_core::vars::Layer::new(
|
||||
knock_core::vars::Scope::Runtime,
|
||||
"runtime",
|
||||
state.runtime_vars(""),
|
||||
));
|
||||
Ok(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct VarsView {
|
||||
pub vars: Vec<VarInfo>,
|
||||
pub dynamic: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn vars_list(state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
|
||||
let ctx = build_context(&state, &args).map_err(errx)?;
|
||||
Ok(VarsView {
|
||||
vars: ctx.resolver.names(),
|
||||
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn runtime_list(state: State<'_, AppState>, col: Option<String>) -> Res<IndexMap<String, String>> {
|
||||
Ok(state.runtime_vars(col.as_deref().unwrap_or("")))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn runtime_set(
|
||||
state: State<'_, AppState>,
|
||||
col: Option<String>,
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
persist: bool,
|
||||
) -> Res<()> {
|
||||
state.set_runtime(col.as_deref().unwrap_or(""), &name, value, persist);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn globals_get(state: State<'_, AppState>) -> Res<IndexMap<String, String>> {
|
||||
db::globals_load(&state.db.lock().unwrap()).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn globals_save(state: State<'_, AppState>, vars: IndexMap<String, String>) -> Res<()> {
|
||||
db::globals_save(&state.db.lock().unwrap(), &vars).map_err(errx)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- sending
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SendArgs {
|
||||
#[serde(flatten)]
|
||||
pub scope: ScopeArgs,
|
||||
pub tab: String,
|
||||
/// Store up to this many bytes of the body in history (0 = none).
|
||||
#[serde(default)]
|
||||
pub history_body_limit: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SendResult {
|
||||
pub output: RunOutput,
|
||||
pub body_id: Option<String>,
|
||||
pub history_id: Option<i64>,
|
||||
pub body_file: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
|
||||
let state = app.state::<AppState>();
|
||||
let ctx = build_context(&state, &args.scope).map_err(errx)?;
|
||||
let engine = state.engine.clone();
|
||||
let req = args.scope.request.clone();
|
||||
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
|
||||
let task = tokio::spawn(async move {
|
||||
let out = execute(&engine, &req, &ctx, Some(&host)).await;
|
||||
(out, ctx)
|
||||
});
|
||||
state.inflight.lock().unwrap().insert(args.tab.clone(), task.abort_handle());
|
||||
let joined = task.await;
|
||||
state.inflight.lock().unwrap().remove(&args.tab);
|
||||
let (mut out, ctx) = match joined {
|
||||
Ok(v) => v,
|
||||
Err(e) if e.is_cancelled() => return Err("cancelled".into()),
|
||||
Err(e) => return Err(err(e)),
|
||||
};
|
||||
|
||||
let col_key = args.scope.col.clone().unwrap_or_default();
|
||||
for x in &out.extracted {
|
||||
if let Some(v) = &x.value {
|
||||
state.set_runtime(&col_key, &x.var, Some(v.clone()), x.persist);
|
||||
}
|
||||
}
|
||||
if let Some(col) = &args.scope.col {
|
||||
let json = state.engine.save_jar(col);
|
||||
let _ = db::jar_save(&state.db.lock().unwrap(), col, &json);
|
||||
}
|
||||
|
||||
let mut body_id = None;
|
||||
let mut body_file = None;
|
||||
let mut stored_body: Option<Vec<u8>> = None;
|
||||
if let Some(resp) = out.response.as_mut() {
|
||||
let body = std::mem::take(&mut resp.body);
|
||||
if args.history_body_limit > 0 && body.len() <= args.history_body_limit && resp.body_file.is_none() {
|
||||
stored_body = Some(body.clone());
|
||||
}
|
||||
body_file = resp.body_file.as_ref().map(|p| p.display().to_string());
|
||||
body_id = Some(state.store_body(body, resp.body_file.clone()));
|
||||
}
|
||||
|
||||
// History never contains secrets in clear text.
|
||||
let mask = |s: &str| ctx.resolver.mask(s);
|
||||
let mut hist_req = args.scope.request.clone();
|
||||
if let Some(sent) = &out.request {
|
||||
hist_req.url = mask(&sent.url);
|
||||
}
|
||||
let req_json = mask(&serde_json::to_string(&hist_req).unwrap_or_default());
|
||||
let meta = out.response.as_ref().map(|r| mask(&serde_json::to_string(r).unwrap_or_default()));
|
||||
let history_id = {
|
||||
let db = state.db.lock().unwrap();
|
||||
db::history_add(
|
||||
&db,
|
||||
db::NewHistory {
|
||||
collection: &col_key,
|
||||
request_id: args.scope.request_id.as_deref(),
|
||||
name: &args.scope.request.name,
|
||||
method: out.request.as_ref().map(|r| r.method.as_str()).unwrap_or(args.scope.request.method()),
|
||||
url: &out.request.as_ref().map(|r| mask(&r.url)).unwrap_or_else(|| args.scope.request.url.clone()),
|
||||
status: out.response.as_ref().map(|r| r.status),
|
||||
duration_ms: out.response.as_ref().map(|r| r.timings.total_ms),
|
||||
size: out.response.as_ref().map(|r| r.size),
|
||||
error: out.error.as_deref(),
|
||||
request_json: &req_json,
|
||||
response_meta: meta.as_deref(),
|
||||
response_body: stored_body.as_deref(),
|
||||
},
|
||||
500 * 1024 * 1024,
|
||||
)
|
||||
.ok()
|
||||
};
|
||||
Ok(SendResult { output: out, body_id, history_id, body_file })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn request_cancel(state: State<'_, AppState>, tab: String) -> Res<()> {
|
||||
if let Some(h) = state.inflight.lock().unwrap().remove(&tab) {
|
||||
h.abort();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Raw body bytes; the frontend decodes them itself.
|
||||
#[tauri::command]
|
||||
pub fn response_body(state: State<'_, AppState>, id: String) -> Res<tauri::ipc::Response> {
|
||||
let guard = state.responses.lock().unwrap();
|
||||
let b = guard.0.get(&id).ok_or("response is no longer available")?;
|
||||
Ok(tauri::ipc::Response::new(b.body.clone()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn response_save(state: State<'_, AppState>, id: String, path: String) -> Res<()> {
|
||||
let guard = state.responses.lock().unwrap();
|
||||
let b = guard.0.get(&id).ok_or("response is no longer available")?;
|
||||
match &b.file {
|
||||
Some(f) => std::fs::copy(f, &path).map(|_| ()).map_err(err),
|
||||
None => std::fs::write(&path, &b.body).map_err(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Preview {
|
||||
pub request: Option<knock_core::run::SentRequest>,
|
||||
pub auth: knock_core::auth::AuthDebug,
|
||||
pub missing: Vec<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// What would be sent, without sending: resolved URL, headers, body and auth.
|
||||
/// OAuth tokens are not fetched here.
|
||||
#[tauri::command]
|
||||
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
||||
let state = app.state::<AppState>();
|
||||
let ctx = build_context(&state, &args).map_err(errx)?;
|
||||
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return Ok(Preview { request: None, auth: Default::default(), missing: vec![], error: Some(errx(e)) })
|
||||
}
|
||||
};
|
||||
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
|
||||
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false).await;
|
||||
Ok(Preview {
|
||||
request: Some(knock_core::run::SentRequest {
|
||||
method: p.method.clone(),
|
||||
url: p.url.clone(),
|
||||
headers: p.headers.clone(),
|
||||
body: match &p.body {
|
||||
knock_core::prepare::PreparedBody::Bytes { preview, .. } => preview.clone(),
|
||||
_ => String::new(),
|
||||
},
|
||||
}),
|
||||
missing: p.missing.clone(),
|
||||
auth,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- cookies
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cookies_list(state: State<'_, AppState>, col: String) -> Res<Vec<knock_core::http::CookieInfo>> {
|
||||
Ok(state.engine.cookies(&col))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cookie_delete(
|
||||
state: State<'_, AppState>,
|
||||
col: String,
|
||||
domain: Option<String>,
|
||||
path: Option<String>,
|
||||
name: Option<String>,
|
||||
) -> Res<()> {
|
||||
match (domain, path, name) {
|
||||
(Some(d), Some(p), Some(n)) => state.engine.delete_cookie(&col, &d, &p, &n),
|
||||
_ => state.engine.clear_cookies(&col),
|
||||
}
|
||||
let json = state.engine.save_jar(&col);
|
||||
db::jar_save(&state.db.lock().unwrap(), &col, &json).map_err(errx)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- history
|
||||
|
||||
#[tauri::command]
|
||||
pub fn history_list(state: State<'_, AppState>, query: String, limit: Option<u32>) -> Res<Vec<db::HistoryEntry>> {
|
||||
db::history_list(&state.db.lock().unwrap(), &query, limit.unwrap_or(300)).map_err(errx)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct HistoryView {
|
||||
pub request: Request,
|
||||
pub response: Option<serde_json::Value>,
|
||||
pub body_id: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn history_get(state: State<'_, AppState>, id: i64) -> Res<HistoryView> {
|
||||
let d = db::history_get(&state.db.lock().unwrap(), id)
|
||||
.map_err(errx)?
|
||||
.ok_or("history entry not found")?;
|
||||
let request: Request = serde_json::from_str(&d.request_json).map_err(err)?;
|
||||
let response = d.response_meta.and_then(|m| serde_json::from_str(&m).ok());
|
||||
let body_id = d.response_body.map(|b| state.store_body(b, None));
|
||||
Ok(HistoryView { request, response, body_id })
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn history_delete(state: State<'_, AppState>, id: Option<i64>) -> Res<()> {
|
||||
db::history_delete(&state.db.lock().unwrap(), id).map_err(errx)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- misc
|
||||
|
||||
#[tauri::command]
|
||||
pub fn setting_get(state: State<'_, AppState>, key: String) -> Res<Option<String>> {
|
||||
db::kv_get(&state.db.lock().unwrap(), &format!("setting.{key}")).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn setting_set(state: State<'_, AppState>, key: String, value: String) -> Res<()> {
|
||||
db::kv_set(&state.db.lock().unwrap(), &format!("setting.{key}"), &value).map_err(errx)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn path_params(url: String) -> Vec<String> {
|
||||
knock_core::prepare::path_param_names(&url)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn app_version() -> String {
|
||||
env!("CARGO_PKG_VERSION").to_string()
|
||||
}
|
||||
Reference in New Issue
Block a user