Cookie jars per folder; pacman repository on Gitea; install guide per platform

- A folder can share its parent's cookie jar, keep its own, or use no
  cookies; sub folders follow. The Cookies tab shows the jar a request
  used. Jars are stored per collection and folder.
- The release workflow builds knock-bin from the deb and uploads it to
  the Gitea pacman repository (needs the GITEA_PACKAGES_TOKEN secret)
- knock-bin installs the desktop entry as knock-app.desktop
- README: install for Arch (signed pacman repo), Ubuntu/Debian,
  Fedora/openSUSE, AppImage, macOS (quarantine) and Windows (SmartScreen)
- release.sh works when the version is already set
This commit is contained in:
2026-11-27 22:12:08 +01:00
parent 59a8000cc0
commit 4b1590e750
13 changed files with 197 additions and 25 deletions
+40
View File
@@ -121,6 +121,46 @@ jobs:
target/release/bundle/rpm/*.rpm
target/release/bundle/appimage/*.AppImage
# Arch package for the pacman repository on Gitea, built from the deb.
# Needs the secret GITEA_PACKAGES_TOKEN (a Gitea token with package write
# access); without it the job is skipped.
arch:
if: startsWith(github.ref, 'refs/tags/v')
needs: [linux]
runs-on: ubuntu-latest
container: archlinux:latest
env:
TOKEN: ${{ secrets.GITEA_PACKAGES_TOKEN }}
REGISTRY: https://git.joshicodes.de/api/packages/JoshiCodes/arch/joshicodes
steps:
- uses: actions/checkout@v5
- uses: actions/download-artifact@v5
with:
name: linux
path: artifacts
- name: Build knock-bin
if: env.TOKEN != ''
run: |
pacman -Syu --noconfirm --needed base-devel
useradd -m builder
deb=$(find artifacts -name '*.deb' | head -1)
tag="${GITHUB_REF_NAME#v}"
ver="${tag//-/}"
mkdir -p /build && cp packaging/arch/knock-bin/PKGBUILD /build/ && cp "$deb" /build/
cd /build
name=$(basename "$deb")
sed -i -E "s/^pkgver=.*/pkgver=$ver/; s/^pkgrel=.*/pkgrel=1/" PKGBUILD
sed -i -E "s|^source=.*|source=(\"$name\")|" PKGBUILD
chown -R builder /build
su builder -c 'makepkg --nodeps --noconfirm'
ls -la *.pkg.tar.zst
- name: Upload to the Gitea pacman repository
if: env.TOKEN != ''
run: |
for f in /build/*.pkg.tar.zst; do
curl --fail-with-body -sS -X PUT --user "JoshiCodes:$TOKEN" --upload-file "$f" "$REGISTRY"
done
release:
if: startsWith(github.ref, 'refs/tags/v')
needs: [macos, linux, windows]
+49 -6
View File
@@ -68,13 +68,56 @@ knock auth debug users --env prod --verbose
## Install
- **Arch Linux / CachyOS:** `packaging/arch/knock-bin` (release package), `packaging/arch/knock` (from source) or `packaging/arch/knock-git` (latest `main`); `makepkg -si` in the folder
- **Ubuntu 22.04+ / Debian:** the `.deb` from the [latest release](https://github.com/JoshiCodes/knock/releases/latest)
- **Fedora and others:** the `.rpm` or the AppImage
- **macOS:** the universal `.dmg` (not notarized: open it once with right click → Open)
- **Windows:** the `.msi` or setup `.exe` (best effort)
Downloads are on the [releases page](https://github.com/JoshiCodes/knock/releases/latest). Every package contains the app (`knock-app`) and the command line tool (`knock`).
If the window stays blank on Wayland, WebKitGTK's DMA-BUF renderer is the usual cause; knock turns it off by default. Set `KNOCK_DMABUF=1` to turn it back on.
### Arch Linux, CachyOS, Manjaro
From the pacman repository (signed). Once:
```sh
curl -fsSL https://git.joshicodes.de/api/packages/JoshiCodes/arch/repository.key | sudo pacman-key --add - && sudo pacman-key --lsign-key B500A6315A9D97708BF6241F10CECFC71020FEB1
printf '\n[joshicodes]\nServer = https://git.joshicodes.de/api/packages/JoshiCodes/arch/$repo/$arch\n' | sudo tee -a /etc/pacman.conf >/dev/null && sudo pacman -Sy knock-bin
```
Updates then come with `sudo pacman -Syu`. Building yourself: `makepkg -si` in `packaging/arch/knock` (release from source) or `packaging/arch/knock-git` (latest `main`).
### Ubuntu 22.04+, Debian, Linux Mint, Pop!_OS
Download `knock_<version>_amd64.deb` from the release and install it:
```sh
sudo apt install ./knock_*_amd64.deb
```
### Fedora, openSUSE
```sh
sudo dnf install ./knock-*.x86_64.rpm # openSUSE: sudo zypper install ./knock-*.x86_64.rpm
```
### Any other Linux
The AppImage runs without installing:
```sh
chmod +x knock_*_amd64.AppImage && ./knock_*_amd64.AppImage
```
It needs `libsecret` (or another Secret Service) for secrets. If the window stays blank on Wayland, start it with `WEBKIT_DISABLE_DMABUF_RENDERER=1` (the packages set this already).
### macOS
Open the universal `knock_<version>_universal.dmg` (Apple Silicon and Intel) and drag knock to Applications. The app is not notarized by Apple, so macOS blocks the first start. Allow it once:
```sh
xattr -dr com.apple.quarantine /Applications/knock.app
```
(or System Settings → Privacy & Security → **Open Anyway** after the first attempt). The command line tool is in `knock-cli-macos-universal.tar.gz`: unpack it and move `knock` to a folder on your `PATH`, e.g. `/usr/local/bin`.
### Windows (best effort)
Run the `.msi` or the setup `.exe`. Windows SmartScreen warns about apps without a code signing certificate: click **More info → Run anyway**. The command line tool is in `knock-cli-windows-x64.zip`.
## Development
+12
View File
@@ -135,6 +135,18 @@ impl Engine {
}
}
/// Ids of loaded jars that belong to a collection (its own and its folders').
pub fn jar_ids(&self, collection: &str) -> Vec<String> {
let prefix = format!("{collection}/");
self.jars
.lock()
.unwrap()
.keys()
.filter(|k| *k == collection || k.starts_with(&prefix))
.cloned()
.collect()
}
pub fn save_jar(&self, collection: &str) -> String {
let jar = self.jar(collection);
let store = jar.lock().unwrap();
+13
View File
@@ -158,10 +158,23 @@ pub struct FolderMeta {
pub headers: Vec<KeyValue>,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub vars: IndexMap<String, String>,
/// Cookie jar for this folder and everything below it. Unset shares the
/// jar of the parent (in the end the collection's).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cookies: Option<CookieJarMode>,
#[serde(flatten)]
pub extra: Extra,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CookieJarMode {
/// A jar of its own, separate from the collection's.
Own,
/// No cookies are stored or sent.
Off,
}
// ---------------------------------------------------------------- request
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+34
View File
@@ -36,6 +36,9 @@ pub struct RequestContext {
pub collection_settings: CollectionSettings,
pub collection_id: String,
pub env: Option<String>,
/// Cookie jar for this request, from the collection setting and the
/// closest folder that sets one; None means no cookies.
pub jar: Option<String>,
}
pub struct ContextInput<'a> {
@@ -83,6 +86,7 @@ impl RequestContext {
}
let auth = effective_auth(c, input.request_id, &input.request.auth, &ancestors);
let jar = cookie_jar(&c.manifest.id, c.manifest.settings.cookies, &ancestors);
let mut inherited_headers = c.manifest.headers.clone();
for (_, meta) in &ancestors {
inherited_headers.extend(meta.headers.iter().cloned());
@@ -95,6 +99,7 @@ impl RequestContext {
collection_settings: c.manifest.settings.clone(),
collection_id: c.manifest.id.clone(),
env: input.env.map(str::to_string),
jar,
})
}
@@ -119,10 +124,28 @@ impl RequestContext {
collection_settings: CollectionSettings::default(),
collection_id: String::new(),
env: None,
jar: None,
}
}
}
/// The jar id a request uses: the collection id, or `<collection>/<folder>`
/// for a folder with a jar of its own.
pub fn cookie_jar(collection_id: &str, collection_cookies: bool, ancestors: &[(String, FolderMeta)]) -> Option<String> {
if collection_id.is_empty() {
return None;
}
let mut jar = collection_cookies.then(|| collection_id.to_string());
for (id, meta) in ancestors {
match meta.cookies {
Some(CookieJarMode::Own) => jar = Some(format!("{collection_id}/{id}")),
Some(CookieJarMode::Off) => jar = None,
None => {}
}
}
jar
}
pub fn effective_auth(
c: &Collection,
request_id: &str,
@@ -540,6 +563,17 @@ mod tests {
assert_eq!(path_param_names("http://h:8080/u/:id/:other?x=:no"), vec!["id", "other"]);
}
#[test]
fn cookie_jar_follows_the_closest_folder() {
let f = |id: &str, mode: Option<CookieJarMode>| (id.to_string(), FolderMeta { cookies: mode, ..Default::default() });
assert_eq!(cookie_jar("c", true, &[]), Some("c".into()));
assert_eq!(cookie_jar("c", false, &[]), None);
assert_eq!(cookie_jar("c", true, &[f("oidc", Some(CookieJarMode::Off))]), None);
assert_eq!(cookie_jar("c", true, &[f("web", Some(CookieJarMode::Own)), f("web/admin", None)]), Some("c/web".into()));
assert_eq!(cookie_jar("c", false, &[f("web", Some(CookieJarMode::Own))]), Some("c/web".into()));
assert_eq!(cookie_jar("c", true, &[f("web", Some(CookieJarMode::Own)), f("web/x", Some(CookieJarMode::Off))]), None);
}
#[test]
fn jsonc() {
let s = "{\n // c\n \"a\": \"http://x\", /* b */\n \"b\": [1,2,],\n}";
+4 -2
View File
@@ -27,6 +27,8 @@ pub struct RunOutput {
pub missing: Vec<String>,
/// The request was sent a second time after refreshing an expired token.
pub retried: bool,
/// Cookie jar the request used, if any.
pub jar: Option<String>,
}
impl RunOutput {
@@ -111,6 +113,7 @@ pub async fn execute(
error: None,
missing: Vec::new(),
retried: false,
jar: if req.settings.cookies { ctx.jar.clone() } else { None },
};
let base = match prepare(req, ctx) {
Ok(p) => p,
@@ -133,8 +136,7 @@ pub async fn execute(
return out;
}
let transport = transport_for(ctx, &p.url);
let jar = (ctx.collection_settings.cookies && !ctx.collection_id.is_empty())
.then_some(ctx.collection_id.as_str());
let jar = ctx.jar.as_deref();
match engine.send(&p, &transport, jar).await {
Ok(resp) if is_digest && resp.status == 401 => {
let challenge = resp
+4
View File
@@ -15,5 +15,9 @@ sha256sums=('SKIP')
package() {
bsdtar -xf data.tar.* -C "$pkgdir"
# KDE matches the window (app id knock-app) to the desktop file by name.
if [ -f "$pkgdir/usr/share/applications/knock.desktop" ]; then
mv "$pkgdir/usr/share/applications/knock.desktop" "$pkgdir/usr/share/applications/knock-app.desktop"
fi
install -Dm644 "$pkgdir/usr/share/doc/knock/copyright" "$pkgdir/usr/share/licenses/$pkgname/LICENSE" 2>/dev/null || true
}
+2 -1
View File
@@ -33,7 +33,8 @@ sed -i -E "s/^pkgver=.*/pkgver=$base/; s/^pkgrel=.*/pkgrel=1/" packaging/arch/kn
cargo update -w --offline >/dev/null 2>&1 || cargo update -w >/dev/null
git add Cargo.toml Cargo.lock package.json package-lock.json src-tauri/tauri.conf.json packaging/arch
git commit -q -m "Release v$v"
# The version may already be set (first release); then there is nothing to commit.
git diff --cached --quiet || git commit -q -m "Release v$v"
git tag -a "v$v" -m "knock $v"
git push -q origin main "v$v"
echo "Pushed v$v. Follow the build: gh run watch \$(gh run list -w release -L1 --json databaseId -q '.[0].databaseId')"
+9 -7
View File
@@ -60,8 +60,8 @@ fn remember_recent(state: &AppState, root: &str) {
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);
for (id, json) in db::jars_for(&state.db.lock().unwrap(), &v.id).unwrap_or_default() {
state.engine.load_jar(&id, &json);
}
let root = c.root.clone();
state.collections.write().unwrap().insert(v.id.clone(), c);
@@ -433,9 +433,9 @@ pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
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);
if let Some(jar) = &out.jar {
let json = state.engine.save_jar(jar);
let _ = db::jar_save(&state.db.lock().unwrap(), jar, &json);
}
let mut body_id = None;
@@ -666,8 +666,10 @@ pub async fn runner_run(
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);
for jar in state.engine.jar_ids(&col) {
let json = state.engine.save_jar(&jar);
let _ = db::jar_save(&state.db.lock().unwrap(), &jar, &json);
}
Ok(RunResult { json: knock_core::runner::to_json(&report), junit: knock_core::runner::to_junit(&report), report })
}
+5 -4
View File
@@ -182,10 +182,11 @@ pub fn history_delete(c: &Connection, id: Option<i64>) -> Result<()> {
Ok(())
}
pub fn jar_load(c: &Connection, collection: &str) -> Result<Option<String>> {
Ok(c
.query_row("SELECT json FROM cookie_jars WHERE collection = ?1", [collection], |r| r.get(0))
.optional()?)
/// The collection's jar and the jars of its folders (`<collection>/<folder>`).
pub fn jars_for(c: &Connection, collection: &str) -> Result<Vec<(String, String)>> {
let mut stmt = c.prepare("SELECT collection, json FROM cookie_jars WHERE collection = ?1 OR collection LIKE ?1 || '/%'")?;
let rows = stmt.query_map([collection], |r| Ok((r.get(0)?, r.get(1)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn jar_save(c: &Connection, collection: &str, json: &str) -> Result<()> {
+2
View File
@@ -146,6 +146,7 @@ export interface FolderMeta {
auth?: Auth;
headers?: KeyValue[];
vars?: Record<string, string>;
cookies?: 'own' | 'off';
[extra: string]: unknown;
}
@@ -308,6 +309,7 @@ export interface RunOutput {
error: string | null;
missing: string[];
retried: boolean;
jar?: string | null;
}
export interface SendResult {
output: RunOutput;
+11 -5
View File
@@ -9,8 +9,12 @@
let resp = $derived(out.response);
let jar = $state<CookieInfo[]>([]);
// The jar the request used: the collection's, a folder's own, or none.
let jarId = $derived(out.jar ?? null);
let jarLabel = $derived(!jarId ? null : jarId.includes('/') ? `folder ${jarId.slice(jarId.indexOf('/') + 1)}` : 'collection');
async function loadJar() {
if (tab.col) jar = await api.cookies(tab.col);
jar = jarId ? await api.cookies(jarId) : [];
}
$effect(() => {
if (cookies) {
@@ -20,8 +24,8 @@
});
async function del(c?: CookieInfo) {
if (!tab.col) return;
await api.cookieDelete(tab.col, c);
if (!jarId) return;
await api.cookieDelete(jarId, c);
loadJar();
}
</script>
@@ -55,9 +59,11 @@
<span class="shrink-0 text-[11px] text-fg-subtle">{c.domain}{c.path} {c.http_only ? 'HttpOnly' : ''} {c.secure ? 'Secure' : ''} {c.same_site ?? ''}</span>
</div>
{/each}
{#if tab.col}
{#if !jarId && tab.col}
<p class="mt-6 text-fg-subtle">This request uses no cookie jar (turned off for the request, its folder or the collection).</p>
{:else if jarId}
<div class="mb-1.5 mt-6 flex items-center">
<span class="k-label flex-1">Cookie jar of this collection</span>
<span class="k-label flex-1">Cookie jar: {jarLabel}</span>
{#if jar.length}<button class="text-[12px] text-fg-muted hover:text-delete" onclick={() => del()}>Clear all</button>{/if}
</div>
{#if !jar.length}<p class="py-1 text-fg-subtle">Empty.</p>{/if}
+12
View File
@@ -69,6 +69,18 @@
<p class="mb-2 text-[12px] text-fg-subtle">Requests in this folder that use "inherit" get this auth.</p>
<div class="-mx-3"><AuthPanel bind:auth={meta.auth!} level="folder" {col} /></div>
</section>
<section>
<h2 class="k-label mb-2">Cookies</h2>
<p class="mb-3 text-[12px] text-fg-subtle">A folder can keep its own cookies, for example a frontend session apart from OIDC tests. Sub folders follow unless they choose something else.</p>
<div class="flex flex-col gap-1.5">
{#each [[undefined, 'Share the cookie jar of the parent folder or collection'], ['own', 'Own cookie jar for this folder'], ['off', 'No cookies']] as [mode, label]}
<label class="flex items-center gap-2">
<input type="radio" name="cookie-mode" class="size-3.5 accent-[var(--knock-cyan)]" checked={meta.cookies === mode} onchange={() => (meta!.cookies = mode as FolderMeta['cookies'])} />
<span>{label}</span>
</label>
{/each}
</div>
</section>
<section>
<h2 class="k-label mb-2">Headers</h2>
<KeyValueTable bind:rows={meta.headers!} nameSuggestions={HEADER_NAMES} valueSuggestions={headerValues} />