299 Commits
409 changed files with 50021 additions and 3198 deletions

No files matched your search

+32 -4
View File
@@ -1,5 +1,33 @@
[build]
target = "armv7-unknown-linux-musleabihf"
[target.armv7-unknown-linux-musleabihf]
linker = "rust-lld"
linker = "rust-lld"
# [target.aarch64-unknown-linux-gnu]
# linker = "aarch64-linux-gnu-gcc"
[build]
# target = "armv7-unknown-linux-musleabihf"
[alias]
cl = "c --target=armv7-unknown-linux-musleabihf"
bl = "b --target=armv7-unknown-linux-musleabihf"
tl = "t --target=armv7-unknown-linux-musleabihf"
cw = "c --target=x86_64-pc-windows-msvc"
bw = "b --target=x86_64-pc-windows-msvc"
tw = "t --target=x86_64-pc-windows-msvc"
check-all = "check --workspace --all-features --all-targets"
clippy-all = "clippy --workspace --all-targets --all-features" # -- -D warnings
test-all = "test --workspace --all-features --all-targets"
fmt-all = "fmt --all"
# idk below
ldar = "r -qrp"
ldabr = "b -r --target=armv7-unknown-linux-musleabihf"
t = "test -- --nocapture --test-threads=1"
tdebug = "test -- --nocapture --test-threads=1 --show-output"
[registries.gitea]
index = "sparse+https://git.ldlda.com/api/packages/lda/cargo/" # Sparse index
+10
View File
@@ -0,0 +1,10 @@
# Live mode (local dev): query! macros validate every query against the real
# schema on each build, so the .sqlx cache is only needed for DB-less builds.
# Run scripts/prepare_sqlx_sqlite.sh once first — it creates and migrates the DB.
# Use an absolute path so builds work from any working directory.
# Replace the placeholder below with the DATABASE_URL printed by the script.
DATABASE_URL=sqlite:///absolute/path/to/wakey-prepare.sqlite3
# Offline mode (CI / packaging): force the committed .sqlx cache.
# Takes precedence over DATABASE_URL when set.
#SQLX_OFFLINE=true
+68 -9
View File
@@ -7,12 +7,19 @@ on:
- "v*"
workflow_dispatch:
env:
# When using cargo-zigbuild for *-gnu targets, link against this glibc baseline (wider VPS compatibility).
WAKEY_CC_GLIBC_VERSION: "2.28"
jobs:
build:
runs-on: [self-hosted, windows]
# My Machine has arm-musl stuff - or else i have to use cross :(
runs-on: [self-hosted, linux, fedora, wsl, release]
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Ensure toolchain and targets
shell: pwsh
@@ -20,6 +27,8 @@ jobs:
rustc -V
cargo -V
rustup target add armv7-unknown-linux-musleabihf
rustup target add x86_64-unknown-linux-gnu
rustup target add aarch64-unknown-linux-gnu
- name: Cache cargo
uses: actions/cache@v4
@@ -28,28 +37,78 @@ jobs:
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
key: linux-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Build (armv7-musl)
shell: pwsh
run: |
cargo build --release --target armv7-unknown-linux-musleabihf
cargo build --release --target armv7-unknown-linux-musleabihf -p wakey -p wakey-agent
- name: Build UI dist
shell: bash
run: |
set -euo pipefail
cd ui
pnpm install --frozen-lockfile
pnpm build
- name: Build control-plane (linux-gnu; zig + older glibc when available)
shell: bash
run: |
set -euo pipefail
GLIBC_VER="${WAKEY_CC_GLIBC_VERSION:-2.28}"
GNU_TARGETS=(x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu)
use_zig=false
if command -v zig >/dev/null 2>&1 && cargo zigbuild -h >/dev/null 2>&1; then
use_zig=true
fi
if [ "$use_zig" = true ]; then
echo "cargo-zigbuild + zig found: building control-plane with glibc ${GLIBC_VER}"
for base in "${GNU_TARGETS[@]}"; do
cargo zigbuild --release --target "${base}.${GLIBC_VER}" -p wakey-control-plane
done
else
echo "zig or cargo zigbuild not available: using plain cargo build (binary needs glibc >= host)"
for base in "${GNU_TARGETS[@]}"; do
cargo build --release --target "$base" -p wakey-control-plane
done
fi
- name: Package rootfs tarball
shell: pwsh
run: |
./scripts/package_rootfs.ps1 -Version "${{ github.ref_name }}" -Target armv7-unknown-linux-musleabihf
- name: Package control-plane bundles
shell: bash
run: |
set -euo pipefail
chmod +x scripts/update_wakey_cc.sh scripts/package_wakey_cc_bundle.sh
for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu; do
./scripts/package_wakey_cc_bundle.sh --version "${{ github.ref_name }}" --target "$target"
done
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: wakey-rootfs
path: dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz
- name: Publish Release to Gitea (API)
- name: Upload control-plane bundles
uses: actions/upload-artifact@v3
with:
name: wakey-cc-bundles
path: dist/wakey-cc-*unknown-linux-gnu.tgz
- name: Publish Release to Gitea
if: startsWith(github.ref, 'refs/tags/')
shell: pwsh
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
./scripts/ci_gitea_release.ps1 -Tag "$env:GITHUB_REF_NAME" -AssetPattern "dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz"
# use their personal repo cuz this searches github.com T_T
uses: akkuman/gitea-release-action@v1
with:
token: ${{ secrets.GITEA_TOKEN }}
files: |
dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz
dist/wakey-cc-*unknown-linux-gnu.tgz
tag_name: ${{ github.ref_name }}
+4 -7
View File
@@ -1,8 +1,5 @@
you should use block code to refence code, like so:
```rust
hello_world!(println);
// indented lines
```
in the chat. Else it fucks up formatting.
We work towards clean, modular, maintainable design, clear documentation... im not the best at this thing, my choices can be bad, so you help me.
We work towards clean, maintainable design. im not the best at this thing.
DRY: spawn subagents.
Context: break those files out.
Test: make functions easy to test.
+59
View File
@@ -0,0 +1,59 @@
name: CI
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
jobs:
rust:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: cargo fmt
run: cargo fmt --all -- --check
- name: cargo clippy
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
- name: cargo test
run: cargo test --workspace --all-features
# Operator UI (`ui/`): same checks you’d run locally before a control-plane bundle.
ui:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ui
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: pnpm
cache-dependency-path: ui/pnpm-lock.yaml
- name: pnpm install
run: pnpm install --frozen-lockfile
- name: TypeScript (no emit)
run: pnpm run typecheck
- name: Prettier
run: pnpm run format:check
- name: Vite production build
run: pnpm run build
+106
View File
@@ -0,0 +1,106 @@
name: release
run-name: Release ${{ github.ref_name }}
on:
push:
tags:
- "v*"
workflow_dispatch:
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-unknown-linux-gnu,aarch64-unknown-linux-gnu
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: pnpm
cache-dependency-path: ui/pnpm-lock.yaml
- name: Install cross
run: cargo install cross --locked
- name: Cache cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: linux-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Build (armv7-musl with cross)
run: |
cross build --release --target armv7-unknown-linux-musleabihf -p wakey -p wakey-agent
- name: Build UI dist
shell: bash
run: |
set -euo pipefail
cd ui
pnpm install --frozen-lockfile
pnpm build
- name: Build control-plane (linux-gnu)
shell: bash
run: |
set -euo pipefail
# x86_64 builds natively; aarch64 needs cross
echo "Building control-plane x86_64-unknown-linux-gnu (native)"
cargo build --release --target x86_64-unknown-linux-gnu -p wakey-control-plane
echo "Building control-plane aarch64-unknown-linux-gnu (cross)"
cross build --release --target aarch64-unknown-linux-gnu -p wakey-control-plane
- name: Package rootfs tarball
shell: pwsh
run: |
./scripts/package_rootfs.ps1 -Version "${{ github.ref_name }}" -Target armv7-unknown-linux-musleabihf
- name: Package control-plane bundles
shell: bash
run: |
set -euo pipefail
chmod +x scripts/update_wakey_cc.sh scripts/package_wakey_cc_bundle.sh
for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu; do
./scripts/package_wakey_cc_bundle.sh --version "${{ github.ref_name }}" --target "$target"
done
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: wakey-rootfs
path: dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz
- name: Upload control-plane bundles
uses: actions/upload-artifact@v4
with:
name: wakey-cc-bundles
path: dist/wakey-cc-*unknown-linux-gnu.tgz
- name: Publish Release to GitHub
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
tag_name: ${{ github.ref_name }}
files: |
dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz
dist/wakey-cc-*unknown-linux-gnu.tgz
+5
View File
@@ -18,3 +18,8 @@ target/
#.idea/
.env
.codex
# sqlx prepare DB (created by scripts/prepare_sqlx_sqlite.sh)
wakey-prepare.sqlite3*
+3
View File
@@ -0,0 +1,3 @@
[submodule "vendor/vt100"]
path = vendor/vt100
url = https://github.com/ldlda/vt100-rust-1
+2
View File
@@ -0,0 +1,2 @@
/cache
/project.local.yml
+12
View File
@@ -0,0 +1,12 @@
# Completion Checklist
Before handing back code changes, run the smallest checks covering the changed area:
- Rust formatting: `cargo fmt`.
- For control-plane SQLx/state/API work: `cargo test -p wakey-control-plane` and `SQLX_OFFLINE=true cargo test -p wakey-control-plane`.
- For SQLx query macro changes: run `scripts/prepare_sqlx_sqlite.sh` and include the `.sqlx` metadata changes.
- For wakey-linux/core inventory/observation work: `cargo test -p wakey-linux -p wakey-core`.
- For agent session/config/protocol work: `cargo test -p wakey-agent`.
- For UI work: `pnpm --dir ui typecheck` and `pnpm --dir ui build`; use `pnpm --dir ui format` when touching TS/TSX/CSS formatting.
- Run relevant `cargo clippy -p <crate> --all-targets --all-features` when behavior or API shape changes.
Always check `git status --short` and mention unrelated dirty files or generated metadata in the final summary.
+14
View File
@@ -0,0 +1,14 @@
# Wakey Project Overview
Wakey is a Wake-on-LAN and LAN observability workspace for Linux/OpenWrt routers. It includes:
- `wakey-core`: shared model and parsing types for devices, neighbors, DHCP, interfaces, wake results.
- `wakey-linux`: Linux/OpenWrt adapter layer for DHCP lease files, neighbor lookup, interface data, WoL sending, and local observation storage.
- root `wakey` crate: service layer and operator CLI for inventory, leases, devs, wake, and observe.
- `wakey-agent`: outbound router daemon. Enrolls with control plane, maintains authenticated websocket, executes relayed commands, syncs observations.
- `wakey-control-plane`: Axum control plane, SQLx SQLite state, agent registry, command relay, known devices, observations, audit/alerts, fleet APIs, static UI hosting.
- `ipjs`: typed wrappers around Linux `ip -j` data.
- `ui`: React/Vite operator UI using shadcn/base-ui style components.
Current persistence direction: control plane uses SQLx SQLite with migrations in `wakey-control-plane/migrations` and offline query metadata in `.sqlx` plus `wakey-control-plane/.sqlx`. Legacy sled import exists as explicit command.
Current product direction: fleet-first device UI and backend. Known device identity is manual. Observations/inventory provide suggestions/current state but should not automatically promote or delete durable identifiers.
+23
View File
@@ -0,0 +1,23 @@
# Style And Conventions
Rust:
- Edition 2024.
- Prefer explicit, small service/API functions over large abstractions.
- Use `anyhow::Context` for fallible operations in application layers.
- Use `tracing` for logs.
- Shared domain types live in `wakey-core`; Linux/OpenWrt I/O in `wakey-linux`; root crate owns service/CLI behavior; agent/control-plane should reuse service/domain types where possible.
- SQLx query macros are used in control-plane state. Regenerate `.sqlx` metadata after query string changes.
- Device identity is manual: observations and inventory may suggest, but should not silently pin, merge, promote, or delete known identifiers.
- Hotplug observation actions should stay event-shaped (`add`, `update`, `remove`). Do not store NUD state as the action. NUD belongs to live neighbor/inventory data.
Frontend:
- React + Vite + TypeScript.
- Use existing component/style conventions; shadcn/base-ui/lucide are available.
- Main operator UI is fleet-first: common path is find device, inspect current IP/MAC/agent, wake, copy, remember/merge.
- Admin/debug pages stay available but should not dominate the primary nav.
Editing:
- Keep changes scoped.
- Preserve user edits in dirty worktrees.
- Use `apply_patch` for manual file edits.
- Default to ASCII unless files already use non-ASCII for a reason.
+31
View File
@@ -0,0 +1,31 @@
# Suggested Commands
Rust formatting and checks:
- `cargo fmt`
- `cargo test -p wakey-control-plane`
- `SQLX_OFFLINE=true cargo test -p wakey-control-plane`
- `cargo test -p wakey-linux -p wakey-core`
- `cargo test -p wakey-agent` (may need elevated permissions if tests bind local sockets)
- `cargo clippy -p wakey-control-plane --all-targets --all-features`
- `cargo clippy -p wakey-linux -p wakey-core --all-targets --all-features`
SQLx metadata after query macro changes:
- `scripts/prepare_sqlx_sqlite.sh`
UI checks:
- `pnpm --dir ui typecheck`
- `pnpm --dir ui build`
- `pnpm --dir ui format`
Local run examples:
- `cargo run -- inventory <query>`
- `cargo run -- leases`
- `cargo run -- devs`
- `cargo run -- wake --mac aa:bb:cc:dd:ee:ff`
- `cargo run -p wakey-agent -- serve --config /etc/wakey-agent/config.toml`
- `cargo run -p wakey-control-plane -- serve --config-file /etc/wakey-control-plane/config.toml`
Useful shell tools:
- Prefer `rg` and `rg --files` for search.
- Use `git status --short`, `git diff --stat`, and focused `git diff -- <path>` before edits.
- Avoid destructive git commands unless explicitly requested.
+155
View File
@@ -0,0 +1,155 @@
# the name by which the project can be referenced within Serena
project_name: "wakey"
# list of languages for which language servers are started; choose from:
# al bash clojure cpp csharp
# csharp_omnisharp dart elixir elm erlang
# fortran fsharp go groovy haskell
# haxe java julia kotlin lua
# markdown
# matlab nix pascal perl php
# php_phpactor powershell python python_jedi r
# rego ruby ruby_solargraph rust scala
# swift terraform toml typescript typescript_vts
# vue yaml zig
# (This list may be outdated. For the current list, see values of Language enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some languages require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple languages, the first language server that supports a given file will be used for that file.
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- rust
- typescript
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
# No documentation on options means no options are available.
ls_specific_settings: {}
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
#
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project based on the project name or path.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_memory`: Delete a memory file. Should only happen if a user asks for it explicitly,
# for example by saying that the information retrieved from a memory file is no longer correct
# or no longer relevant for the project.
# * `edit_memory`: Replaces content matching a regular expression in a memory.
# * `execute_shell_command`: Executes a shell command.
# * `find_file`: Finds files in the given relative paths
# * `find_referencing_symbols`: Finds symbols that reference the given symbol using the language server backend
# * `find_symbol`: Performs a global (or local) search using the language server backend.
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Provides instructions Serena usage (i.e. the 'Serena Instructions Manual')
# for clients that do not read the initial instructions when the MCP server is connected.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: List available memories. Any memory can be read using the `read_memory` tool.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Read the content of a memory file. This tool should only be used if the information
# is relevant to the current task. You can infer whether the information
# is relevant from the memory file name.
# You should not read the same memory file multiple times in the same conversation.
# * `rename_memory`: Renames or moves a memory. Moving between project and global scope is supported
# (e.g., renaming "global/foo" to "bar" moves it from global to project scope).
# * `rename_symbol`: Renames a symbol throughout the codebase using language server refactoring capabilities.
# For JB, we use a separate tool.
# * `replace_content`: Replaces content in a file (optionally using regular expressions).
# * `replace_symbol_body`: Replaces the full definition of a symbol using the language server backend.
# * `safe_delete_symbol`:
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `write_memory`: Write some information (utf-8-encoded) about this project that can be useful for future tasks to a memory in md format.
# The memory name should be meaningful.
excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
fixed_tools: []
# list of mode names to that are always to be included in the set of active modes
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this setting overrides the global configuration.
# Set this to [] to disable base modes for this project.
# Set this to a list of mode names to always include the respective modes for this project.
base_modes:
# list of mode names that are to be activated by default.
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# This setting can, in turn, be overridden by CLI parameters (--mode).
default_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO agents (agent_id, agent_token) VALUES (?1, ?2)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "020b33576bfc2d171a051f903d40ccc78c972fa9d5d983a5678f03abbc8b8488"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT OR REPLACE INTO enroll_tokens (token, expires_at_unix) VALUES (?1, ?2)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "07d7f283daba2742e5522abf99074171ed484c03f70138be611e0c4b17e311b8"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_devices WHERE agent_id = ?1 AND device_key = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "09db61a070a351a6255e21d5949285ccb19fca7f8f29a6c18dddac5495257a45"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO audit_events\n (event_key, event_id, ts_unix, actor_type, actor_id, agent_id, request_id,\n event_type, outcome, latency_ms, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
"describe": {
"columns": [],
"parameters": {
"Right": 12
},
"nullable": []
},
"hash": "0c47aade9d5c71d6c7e2023c6ff66c6ab4b3a0dd2b78af3a600dedc89da508f2"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) as \"count!: i64\" FROM enroll_tokens",
"describe": {
"columns": [
{
"name": "count!: i64",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false
]
},
"hash": "0ca58d0cbc25c59d2c956222d41c02eb0c76a135f29a56a7570b750f7378738d"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", fact_json as \"fact_json!\"\n FROM agent_device_facts",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "fact_json!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false
]
},
"hash": "12e443ec0991c042cf527498b567bbbb6d02885f72eb3fa426c9493368f8a9e7"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO agent_meta (agent_id, nickname) VALUES (?1, ?2)\n ON CONFLICT(agent_id) DO UPDATE SET nickname = excluded.nickname",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "181992e554afdd8f21bd5df71bfb7880a5a9de28af8cd0c766d8d4aa649b3c90"
}
@@ -0,0 +1,50 @@
{
"db_name": "SQLite",
"query": "SELECT device_id as \"device_id!\", display_name as \"display_name!\",\n pinned, created_at_unix, updated_at_unix, notes\n FROM known_devices\n ORDER BY pinned DESC, display_name, device_id",
"describe": {
"columns": [
{
"name": "device_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "display_name!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "pinned",
"ordinal": 2,
"type_info": "Integer"
},
{
"name": "created_at_unix",
"ordinal": 3,
"type_info": "Integer"
},
{
"name": "updated_at_unix",
"ordinal": 4,
"type_info": "Integer"
},
{
"name": "notes",
"ordinal": 5,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
true,
false,
false,
false,
false,
true
]
},
"hash": "19b5fc20ffc99589bbaf11b94661f7c0dfcf80748c60f8f3289bb3296114635a"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) as \"count!: i64\" FROM agents",
"describe": {
"columns": [
{
"name": "count!: i64",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false
]
},
"hash": "21e5986ad3e8efd3393f2bc4929ee79e664cbc2b55948c276d52ca2a6fdc6a48"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO known_devices\n (device_id, display_name, pinned, created_at_unix, updated_at_unix, notes)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
"describe": {
"columns": [],
"parameters": {
"Right": 6
},
"nullable": []
},
"hash": "2bff8b8b070f5b5dd946e754c5e15ea405f6c29baa4c2c31347f455227437ae2"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT 1 as \"ok!\"",
"describe": {
"columns": [
{
"name": "ok!",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false
]
},
"hash": "2c0dd5d9be90cc716da219c75c2d3b75dae8c0902c64ef5baa96c902f23abc5d"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_device_hostnames WHERE agent_id = ?1 AND device_key = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "2cd47bbce9b9ae2ebf39f31b12722bb8d19ef6d90ac634731932a4cefbde03b7"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT device_key FROM agent_devices WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "device_key",
"ordinal": 0,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "3f24dfb51be2c3051dc8a8f732bd3e3fe9ca6b2649e1202d3725693b8011f269"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", hostname as \"hostname!\"\n FROM agent_device_hostnames\n WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "hostname!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false
]
},
"hash": "4188fb9a0dac2e19fb1f83e023eb1e8d93f6ca896cd78a53668080639fc048d9"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", ip as \"ip!\"\n FROM agent_device_ips",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "ip!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false
]
},
"hash": "4dd5e580826b0f6980bb8c2adecdc81ff95992ec337f93263463c5a4e357dc72"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_device_macs WHERE agent_id = ?1 AND device_key = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "4f4329b0a47a00a3b881a1bc5cf8bb9855351714ff827ccff917b3e623191504"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) as \"count!: i64\" FROM enroll_tokens WHERE expires_at_unix <= ?1",
"describe": {
"columns": [
{
"name": "count!: i64",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "5083fd5878c57f4d54e8b24ad0cef2771f7cac36afb7c370c65137fc0784f093"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agents WHERE agent_id = ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "51cb6ec47368803af60114a39dd9e70ba9d31946bc39980c9e85dbc4e842a2c8"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT expires_at_unix FROM enroll_tokens WHERE token = ?1",
"describe": {
"columns": [
{
"name": "expires_at_unix",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "540f57604aa987b97930bb0bcfe440094d97b769fd758fd5cffc32f6d5716bb4"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_device_facts WHERE agent_id = ?1 AND device_key = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "55340d50a29e0a2d324ed946b6fa6503fbd4ea0674bb7ec24e3426c5b0e5832f"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", mac as \"mac!\"\n FROM agent_device_macs\n WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "mac!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false
]
},
"hash": "580f6bc100d373137db6f853b8babd7633c700dbfaf17ded507b704fd98e46a5"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", mac as \"mac!\"\n FROM agent_device_macs",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "mac!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false
]
},
"hash": "5824c6cb841f7aaeb2a039f846effe17ba8038e35998b674136a19a4d42d8b88"
}
@@ -0,0 +1,50 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id, device_key, presence, display_name,\n first_seen_unix, last_seen_unix\n FROM agent_devices\n WHERE agent_id = ?1\n ORDER BY device_key",
"describe": {
"columns": [
{
"name": "agent_id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "presence",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "display_name",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "first_seen_unix",
"ordinal": 4,
"type_info": "Integer"
},
{
"name": "last_seen_unix",
"ordinal": 5,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false,
true,
false,
false
]
},
"hash": "5f7e043ca389f1431c7b3478ea506b0c9bb706d32c06871d1267068dbe9cb746"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) as \"count!: i64\" FROM agents WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "count!: i64",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "60c6631ace995d7ca109d1bee1d878c823edd40f15f8571b42e00680a120ad74"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO alert_transitions\n (transition_key, transition_id, ts_unix, alert_id, kind, agent_id,\n from_status, to_status, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
"describe": {
"columns": [],
"parameters": {
"Right": 10
},
"nullable": []
},
"hash": "69601f4f2268a759f03a2d533a0a30dec5cf05797817fd8d2426714cd84d7ada"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO audit_events\n (event_key, event_id, ts_unix, actor_type, actor_id, agent_id, request_id,\n event_type, outcome, latency_ms, message, metadata_json)\n VALUES (?1, ?2, ?3, 'test', NULL, NULL, NULL, 'test', 'ok', NULL, 'old', '{}')",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "6ce45cc94cbfdd948aad5fb986f9b5976c79bb63759bc9ecff1a7873e2d70137"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE device_identifiers SET device_id = ?1 WHERE device_id = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "7247cc488921de2313a602697590502771a231bde7d03cd9ccac55a70971da45"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM device_identifiers WHERE device_id = ?1 AND identifier_key = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "72aadefca9851a8becdd2dcce54b646aff095b64cef9837f5e8e4ea8dde71d02"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM active_alerts",
"describe": {
"columns": [],
"parameters": {
"Right": 0
},
"nullable": []
},
"hash": "72afd48584f822116318c623f7dd42ddf4c82b337d8a3d52ed5973d52e08c163"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO device_identifiers\n (identifier_key, device_id, kind, value, created_at_unix)\n VALUES (?1, ?2, ?3, ?4, ?5)",
"describe": {
"columns": [],
"parameters": {
"Right": 5
},
"nullable": []
},
"hash": "7dc7edbbe5539f89783cbccb0475e676cb6d369b676b0c5aaedf99854ffbd760"
}
@@ -0,0 +1,26 @@
{
"db_name": "SQLite",
"query": "SELECT token as \"token!\", expires_at_unix FROM enroll_tokens ORDER BY expires_at_unix, token",
"describe": {
"columns": [
{
"name": "token!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "expires_at_unix",
"ordinal": 1,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
true,
false
]
},
"hash": "7f6c5c108953cd4eda8f4e1d4f4db6b3b88270d3d7087b2948362d0ea94ad246"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE known_devices SET display_name = ?1, updated_at_unix = ?2 WHERE device_id = ?3",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "897b794a7f94af42b545d74a5b859850fc9935f40385061b029fab5892a2aded"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_meta WHERE agent_id = ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "8bf8470846bd228d2ea9b243f70f946f002915b9b1983bce818abc0ae3dd97f0"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM enroll_tokens WHERE token = ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "8f3499a2f461f738711b9942a9c9d6254c1f7ed0db54db8b3d65e10fa8dadfc9"
}
@@ -0,0 +1,26 @@
{
"db_name": "SQLite",
"query": "SELECT agents.agent_id as \"agent_id!\", agent_meta.nickname\n FROM agents\n LEFT JOIN agent_meta ON agent_meta.agent_id = agents.agent_id\n ORDER BY agents.agent_id",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "nickname",
"ordinal": 1,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
true,
true
]
},
"hash": "977adb8bdfb9e031a738055fb81c02c6180ca9c37c90e39b3e4efb9168bd1944"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) as \"count!: i64\" FROM meta WHERE key = ?1",
"describe": {
"columns": [
{
"name": "count!: i64",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "9f5d340530083d040794bed2a45b01522f57dc4132184dab0eb32d1b6811992d"
}
@@ -0,0 +1,50 @@
{
"db_name": "SQLite",
"query": "SELECT device_id as \"device_id!\", display_name as \"display_name!\",\n pinned, created_at_unix, updated_at_unix, notes\n FROM known_devices\n WHERE device_id = ?1",
"describe": {
"columns": [
{
"name": "device_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "display_name!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "pinned",
"ordinal": 2,
"type_info": "Integer"
},
{
"name": "created_at_unix",
"ordinal": 3,
"type_info": "Integer"
},
{
"name": "updated_at_unix",
"ordinal": 4,
"type_info": "Integer"
},
{
"name": "notes",
"ordinal": 5,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
true,
false,
false,
false,
false,
true
]
},
"hash": "9fe9f41d6716305ffebc764a72a3aea11e4ba348fae664aa6ba4bffbb3a2bf34"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT device_id FROM device_identifiers WHERE identifier_key = ?1",
"describe": {
"columns": [
{
"name": "device_id",
"ordinal": 0,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "a1bca2de4e1328fa066d5a8703ef5b8bda560b234b9f1e75093827efeac10eec"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO agent_devices (agent_id, device_key, presence, display_name, first_seen_unix, last_seen_unix)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6)\n ON CONFLICT (agent_id, device_key) DO UPDATE SET\n presence = excluded.presence,\n display_name = excluded.display_name,\n last_seen_unix = excluded.last_seen_unix",
"describe": {
"columns": [],
"parameters": {
"Right": 6
},
"nullable": []
},
"hash": "a29f58cb7dd1b1bc510a0d04ecd1dbc7250824ba089dbc36ed9ac2e6dc920fd7"
}
@@ -0,0 +1,68 @@
{
"db_name": "SQLite",
"query": "SELECT transition_id as \"transition_id!\", ts_unix, alert_id as \"alert_id!\",\n kind as \"kind!\", agent_id, from_status, to_status as \"to_status!\",\n message as \"message!\", metadata_json as \"metadata_json!\"\n FROM alert_transitions\n ORDER BY transition_key DESC\n LIMIT ?1",
"describe": {
"columns": [
{
"name": "transition_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "ts_unix",
"ordinal": 1,
"type_info": "Integer"
},
{
"name": "alert_id!",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "kind!",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "agent_id",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "from_status",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "to_status!",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "message!",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "metadata_json!",
"ordinal": 8,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false,
false,
true,
true,
false,
false,
false
]
},
"hash": "a34accb5d8ef1fc90e1029b808956c85fa7cb00c0e879f27bbb99b5a76b5e151"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\" FROM agents ORDER BY agent_id",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
true
]
},
"hash": "a5baac2d2f6dc38946ff15f6cba46ac085780e6521ba23a605a78b4b92a62073"
}
@@ -0,0 +1,74 @@
{
"db_name": "SQLite",
"query": "SELECT alert_id as \"alert_id!\", kind as \"kind!\", severity as \"severity!\",\n status as \"status!\", agent_id, message as \"message!\",\n value, threshold, last_seen_unix, metadata_json as \"metadata_json!\"\n FROM active_alerts",
"describe": {
"columns": [
{
"name": "alert_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "kind!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "severity!",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "status!",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "agent_id",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "message!",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "value",
"ordinal": 6,
"type_info": "Integer"
},
{
"name": "threshold",
"ordinal": 7,
"type_info": "Integer"
},
{
"name": "last_seen_unix",
"ordinal": 8,
"type_info": "Integer"
},
{
"name": "metadata_json!",
"ordinal": 9,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
true,
false,
false,
false,
true,
false,
false,
false,
false,
false
]
},
"hash": "b031d0fa0f9d0640555fc78b400b7bb951a3f013715fb5be51030c2be63e864d"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM known_devices WHERE device_id = ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "b1c6150ef7bd67ce78f8934fc5d451b36f5bed834d39bdde01356e331c5e5ddb"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) FROM alert_transitions WHERE transition_id = ?1",
"describe": {
"columns": [
{
"name": "COUNT(*)",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "b324587b94ee2e98dc8eff5f6735303a2784b74f49068ce8e946cedcd8d12c4e"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT value FROM meta WHERE key = ?1",
"describe": {
"columns": [
{
"name": "value",
"ordinal": 0,
"type_info": "Blob"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "b805f8dada38af1c79a7b3bbc063fd949bf81757705ace7173658de9f185868b"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) FROM audit_events WHERE message = ?1",
"describe": {
"columns": [
{
"name": "COUNT(*)",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "bd1666cea8840df04ddcdc8a0c42b9b7771f9bf63c45613c4b6f8b86be479d70"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO enroll_tokens (token, expires_at_unix) VALUES (?1, ?2)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "bee62978a2ce59095f9bc679258b5747e074a55d52c43b982ea019c79aff1479"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", ip as \"ip!\"\n FROM agent_device_ips\n WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "ip!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false
]
},
"hash": "c423e005d85659547302f506380ad217cc31329262a1c0254ef532653b3a37bb"
}
@@ -0,0 +1,68 @@
{
"db_name": "SQLite",
"query": "SELECT transition_id as \"transition_id!\", ts_unix, alert_id as \"alert_id!\",\n kind as \"kind!\", agent_id, from_status, to_status as \"to_status!\",\n message as \"message!\", metadata_json as \"metadata_json!\"\n FROM alert_transitions\n WHERE ts_unix >= ?1\n ORDER BY transition_key DESC\n LIMIT ?2",
"describe": {
"columns": [
{
"name": "transition_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "ts_unix",
"ordinal": 1,
"type_info": "Integer"
},
{
"name": "alert_id!",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "kind!",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "agent_id",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "from_status",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "to_status!",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "message!",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "metadata_json!",
"ordinal": 8,
"type_info": "Text"
}
],
"parameters": {
"Right": 2
},
"nullable": [
false,
false,
false,
false,
true,
true,
false,
false,
false
]
},
"hash": "ca117e134d45464a8930d0483ff8670d2798f38718c67f49adce06f74656bf2c"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM audit_events WHERE ts_unix < ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "ca612fee8c80f815b33dbc088cc7e0a7552f1f4e38390959e14ea5cc765bf2c7"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_devices WHERE last_seen_unix < ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "cc4b885c31f965013ccaa6f8ae33f6c8d68898654fc0873682c8212339088306"
}
@@ -0,0 +1,50 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id, device_key, presence, display_name,\n first_seen_unix, last_seen_unix\n FROM agent_devices\n ORDER BY agent_id, device_key",
"describe": {
"columns": [
{
"name": "agent_id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "presence",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "display_name",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "first_seen_unix",
"ordinal": 4,
"type_info": "Integer"
},
{
"name": "last_seen_unix",
"ordinal": 5,
"type_info": "Integer"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false,
true,
false,
false
]
},
"hash": "cd8585b9431d223962c376a2d463f0ca8128e7759c8694631f41db0cbd8eb221"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM alert_transitions WHERE ts_unix < ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "ce850a32c8702595bbc3207bf86d53209c48be145562192b3a8f84903d39eac1"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE known_devices SET updated_at_unix = ?1 WHERE device_id = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "d2c2ce1761d22477164b3e5cfde9718877b3b472886ae1dc7e64dc36ad75b2ea"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM agent_device_ips WHERE agent_id = ?1 AND device_key = ?2",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "d442949dce7a4b9a8af97dc34fc34608029564740ad327c525c7f1466bc18a11"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", hostname as \"hostname!\"\n FROM agent_device_hostnames",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "hostname!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false
]
},
"hash": "dba637bf03d53bf3394ead0f01466f9a72fafc54f9ce239d2e5ac7f76b63b168"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) FROM audit_events WHERE event_id = ?1",
"describe": {
"columns": [
{
"name": "COUNT(*)",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "dc7056b7421dcc83648cbd360273ebcce1156ce0f7da2d39f054025ab9b66b6b"
}
@@ -0,0 +1,44 @@
{
"db_name": "SQLite",
"query": "SELECT identifier_key as \"identifier_key!\", device_id as \"device_id!\",\n kind as \"kind!\", value as \"value!\", created_at_unix\n FROM device_identifiers\n WHERE device_id = ?1\n ORDER BY kind, value",
"describe": {
"columns": [
{
"name": "identifier_key!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_id!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "kind!",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "value!",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "created_at_unix",
"ordinal": 4,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
true,
false,
false,
false,
false
]
},
"hash": "dd1d6ba80d6380cb07227eac0b90951c93f63dc4c89349cf1920405943e2093a"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT agent_token FROM agents WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "agent_token",
"ordinal": 0,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "e0def02317412d21994af8d7770a9e717f4be97e022c0f2022983d59391c775b"
}
@@ -0,0 +1,32 @@
{
"db_name": "SQLite",
"query": "SELECT agent_id as \"agent_id!\", device_key as \"device_key!\", fact_json as \"fact_json!\"\n FROM agent_device_facts\n WHERE agent_id = ?1",
"describe": {
"columns": [
{
"name": "agent_id!",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "device_key!",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "fact_json!",
"ordinal": 2,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false
]
},
"hash": "e6be4d9782f66f98ebe4d4b6ec6e93ea9efe8e4c7f1147e1ff68d41a311d57f9"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO alert_transitions\n (transition_key, transition_id, ts_unix, alert_id, kind, agent_id,\n from_status, to_status, message, metadata_json)\n VALUES (?1, ?2, ?3, 'alert-old', 'test', NULL, NULL, 'active', 'old', '{}')",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "e83a43217a3bfaacd2f5e76df1fd05447558646fb2b47963751a7ab53b3a99b6"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "DELETE FROM enroll_tokens WHERE expires_at_unix <= ?1",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "ee6d28dc501f6bb8cf1249ad03b82e3554f1167d5056f02a0cc823601f480e53"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) as \"count!: i64\" FROM known_devices WHERE device_id = ?1",
"describe": {
"columns": [
{
"name": "count!: i64",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "f18ab386ab1961e938ae7fec3e752bdd958118aa4ca81cab3421ac5827b04029"
}
@@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT COUNT(*) FROM enroll_tokens WHERE token = ?1",
"describe": {
"columns": [
{
"name": "COUNT(*)",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "f5a815d4d6e3d088aba3cd01607764d89afaae6108aad0d17e93b1bfc9f7e772"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO active_alerts\n (alert_id, kind, severity, status, agent_id, message, value, threshold,\n last_seen_unix, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
"describe": {
"columns": [],
"parameters": {
"Right": 10
},
"nullable": []
},
"hash": "fa09ff199445b7bf689ef4426cbd20d89040230ffff977cc1b4c73b499b1b33f"
}
@@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO meta (key, value) VALUES (?1, ?2)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "ffed939cfeecca1d46bdf77b67aca2919b34d496e729ad08f87ac9782fb8e382"
}
+2 -2
View File
@@ -1,4 +1,4 @@
{
"rust-analyzer.cargo.target": "armv7-unknown-linux-musleabihf",
"rust-analyzer.diagnostics.disabled": ["unlinked-file"]
}
// "rust-analyzer.diagnostics.disabled": ["unlinked-file"]
}
+146
View File
@@ -0,0 +1,146 @@
# Wakey
Wakey models devices discovered on a local network and the control-plane view used to wake and manage them across agents.
## Language
**Device**:
An operator-facing aggregate that represents one discovered network identity candidate.
_Avoid_: Host, machine, route
**Device Summary**:
The derived names, MACs, IPs, and presence shown on a device aggregate.
_Avoid_: Source of truth, route data
**Endpoint**:
One observed network contact point for a device, including the agent/source, optional MAC, optional IP, presence, and observation time.
_Avoid_: Raw observation, route, IP row
**Endpoint Source**:
The typed origin of an endpoint, such as neighbor data, DHCP lease data, or a hotplug hook.
_Avoid_: String kind, source label
**Observation Fact**:
Debug evidence copied from local observation inputs before it is interpreted into endpoints.
_Avoid_: Endpoint, identifier, source of truth
**Presence**:
The current reachability interpretation for a device or endpoint.
_Avoid_: Endpoint state, status
**Wake Route**:
An endpoint that has enough information and agent availability to attempt waking a device.
_Avoid_: Device, endpoint when not wakeable
**Known Device**:
A device identity manually curated by the operator.
_Avoid_: Auto-pinned device, saved observation
**Identifier**:
A manually approved MAC or IP value that links an observed device or endpoint to a known device.
_Avoid_: Observation key, route id
**Endpoint Key**:
The typed identity of endpoint evidence, based on source and optional MAC/IP.
_Avoid_: Stringly typed route id
**Agent Endpoint Key**:
An endpoint key scoped to the agent that observed it.
_Avoid_: Concatenated agent/source/MAC/IP string
**Agent**:
A fleet member that observes local network state and sends device snapshots to the control plane.
_Avoid_: Router when referring to the software actor
**Agent Host**:
The machine running an agent, including host identity and runtime metadata.
_Avoid_: Device when referring to the agent machine
**Agent Capability**:
Something an agent host can observe or do on the network.
_Avoid_: Router flag
**Terminal Capability**:
An explicitly enabled agent capability that allows the agent host to create remote PTY sessions.
_Avoid_: Command runner, implicit root access
**Terminal Session**:
One operator attachment to one PTY process hosted by an agent.
_Avoid_: Command, SSH session, stored shell
**Terminal Relay**:
The control plane's in-memory pairing of one operator terminal socket with one outbound agent terminal socket.
_Avoid_: Terminal session storage, terminal emulator
**Interface Telemetry**:
Current operational measurements for a network interface visible to an agent.
_Avoid_: Endpoint state, device presence
## Relationships
- A **Device** has zero or more **Endpoints**.
- A **Device Summary** is derived from a **Device** and its **Endpoints**.
- Local source rows are grouped into **Devices** by endpoint-derived **DeviceId**, not by exact **Endpoint Key**.
- Within one complete local snapshot, MAC+IP endpoints may absorb IP-only endpoints with the same IP; this merge is not remembered across snapshots unless the operator creates an **Identifier**.
- An **Endpoint** belongs to exactly one **Agent**.
- An **Endpoint** has one **Endpoint Key**.
- An **Agent Endpoint Key** combines an **Agent** with an **Endpoint Key**.
- An **Endpoint** may have both MAC and IP, MAC only, or IP only.
- An **Endpoint** has exactly one **Endpoint Source**.
- An **Endpoint** has one **Presence**.
- An **Endpoint** may name the network interface where it was observed.
- An **Observation Fact** may explain why an **Endpoint** exists, but does not define identity or wakeability.
- A **Wake Route** is derived from exactly one **Endpoint**.
- A **Wake Route** may carry the interface from its source **Endpoint**.
- A **Known Device** has zero or more **Identifiers**.
- An **Identifier** can link observed **Devices** or **Endpoints** to one **Known Device**.
- An **Agent** runs on one **Agent Host**.
- An **Agent Capability** describes what an **Agent Host** can observe or do.
- **Terminal Capability** is an **Agent Capability** and must be explicitly enabled before an agent can host a **Terminal Session**.
- A **Terminal Session** owns one PTY and is independent of one-shot agent commands.
- A **Terminal Relay** pairs exactly one operator socket with exactly one agent socket for a **Terminal Session**.
- **Interface Telemetry** describes an **Agent Host** interface, not a **Device Endpoint**.
## Example dialogue
> **Dev:** "This **Device** has three IPs. Which one should the UI wake?"
> **Domain expert:** "Do not infer that from the **Device** summary. Use the **Wake Routes** derived from its **Endpoints**."
## Flagged ambiguities
- "route" was used for both observed network contact points and wakeable paths — resolved: use **Endpoint** for observed contact points and **Wake Route** only when the endpoint can be used for wake.
- "device" was used for both an identity aggregate and each MAC/IP pair — resolved: use **Device** for the aggregate and **Endpoint** for each observed MAC/IP/source/state tuple.
- `Device.ips` and `Device.macs` are true summary values, but they are not authoritative for wake, freshness, or per-IP state decisions — resolved: use **Endpoint** for those decisions.
- MAC-only and IP-only observations are still **Endpoints** — resolved: **Wake Routes** require a MAC and a connected **Agent**, while IP is optional route detail.
- Endpoint-specific states such as "removed" or "stale" are not separate concepts yet — resolved: use **Presence** until a distinction appears that presence cannot express cleanly.
- Endpoint origin is not a free string — resolved: use **Endpoint Source** for domain logic and reserve raw strings for debug facts only.
- Local observation file rows map naturally to **Observation Facts** — resolved: keep them for debugging, but do not use them as the operational model.
- Offline **Endpoints** remain part of the API model — resolved: UI may collapse them from the primary view, but the API should still expose them for details, copy, and debugging.
- **Device Summary** IPs come only from concrete live-ish sources such as neighbor table rows and current DHCP lease rows — resolved: hotplug hook memory creates **Endpoints** and **Observation Facts**, but does not directly inflate summary IPs.
- Router-ness is not a boolean domain concept — resolved: model **Agent Capabilities** and **Agent Host** metadata instead.
- **Presence** ordering should treat **Unknown** as non-voting/no evidence, weaker than **Offline** — resolved: concrete offline evidence should not be overridden by unknown hook or DHCP ambiguity.
- **Device** presence is derived from all **Endpoints**, not only summary-eligible endpoints.
- Current DHCP leases are summary-eligible **Endpoints** with **Unknown** presence; they may support wake when a MAC is present, but they do not prove reachability.
- DHCP hook events, including removal, indicate **Unknown** because they describe lease churn rather than reachability.
- Neighbor table and neighbor hook events may indicate **Offline** when they report failed or removed reachability.
- **Presence** and wakeability are separate: an **Offline** endpoint may still produce a **Wake Route** if it has a MAC and a connected **Agent**.
- **Endpoint** does not store wakeability; wakeability is derived from endpoint data plus **Agent** runtime and capability context.
- Preferred **Wake Routes** are ordered by connected agent, wakeability, having an IP, presence quality, recency, then source quality.
- **Endpoint** evidence preserves source-specific rows; equivalent **Wake Routes** may ignore source when they target the same agent, MAC, and IP.
- The control plane stores **Endpoints** as structured data so fleet search, identity matching, and wake route selection do not depend on parsing opaque device JSON.
- Summary MAC/IP collections are derived from **Endpoints**; separate MAC/IP storage should be removed or represented as views rather than maintained as independent truth.
- API arrays should be domain-sorted by default; UI may sort top-level fleet rows for presentation, but route ranking and recommended route selection are backend-owned.
- The main fleet API embeds **Endpoints** in each **Device** response; a separate endpoint API is unnecessary until payload size or access patterns require it.
- The control plane stores current per-agent endpoint snapshots, not endpoint event history.
- Agent-local hook memory is retained by local last-seen age policy, not by control-plane acknowledgement; default retention is 7 days unless configured otherwise.
- Live-source **Endpoints** use snapshot time as their observed time; hook-derived **Endpoints** use the hook row's recorded last-seen time.
- **DeviceId**, **Endpoint Key**, and **Agent Endpoint Key** are typed concepts; string keys are boundary serialization only.
- **DeviceId** is derived from a device's **Endpoints**: canonical MAC if any endpoint has a MAC, otherwise canonical IP, otherwise absent.
- Hostnames are endpoint evidence/display data, not part of **Endpoint Key** identity.
- Interface names are endpoint metadata, not part of **Endpoint Key** identity; multi-segment routers may require scoped endpoint identity later if the same source/MAC/IP has different meaning on different interfaces.
- An **Endpoint Key** must contain at least one network address value: MAC, IP, or both. Facts without MAC or IP remain **Observation Facts** only.
- **Identifiers** are source-independent ownership claims over MAC or permanent IP values, not claims over endpoint sources.
- IP **Identifiers** are explicit operator claims; Wakey does not infer whether an IP is permanent, static, or reserved.
- **Terminal Sessions** are not agent commands — resolved: command dispatch remains request/result, while terminals use dedicated streaming sockets.
- **Terminal Relay** is ephemeral control-plane state — resolved: terminal bytes and scrollback are not stored or audited.
- Terminal input, output, and terminal-generated control sequences are byte streams; only lifecycle and resize operations are structured terminal protocol messages.
Generated
+3573 -322
View File
File diff suppressed because it is too large. Load diff
+54 -17
View File
@@ -1,28 +1,65 @@
[package]
name = "wakey"
version = "0.1.5"
version = "0.3.7"
edition = "2024"
publish = ["gitea"]
[dependencies]
axum = { version = "0.8.4", features = ["macros"] }
axum-extra = { version = "0.10.1", features = ["query"] }
color-eyre = "0.6.5"
futures = "0.3.31"
macaddr = { version = "1.0.1", features = ["serde", "serde_std"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_html_form = "0.2.7"
serde_json = "1.0.143"
serde_with = { version = "3.14.0", features = ["json"] }
strum = { version = "0.27.2", features = ["derive", "strum_macros"] }
thiserror = "2.0.16"
tokio = { version = "1.47.1", features = ["fs", "process", "rt-multi-thread", "io-util"] }
urlencoding = "2.1.3"
anyhow = "1"
chrono = { version = "0.4", default-features = false, features = ["clock"] }
clap = { version = "4", features = ["derive"] }
color-eyre = "0"
comfy-table = "7"
futures = "0"
macaddr = { version = "1", features = ["serde", "serde_std"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = [
"fs",
"process",
"rt-multi-thread",
"io-util",
"macros",
"time",
] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
[profile.release]
opt-level = "z"
strip = true
[features]
default = ["very-smart-parsing"]
very-smart-parsing = [] # this is the a-bit-redundant parse thing that copilot made
[workspace]
members = ["ipjs", "wakey-agent", "wakey-control-plane", "wakey-core", "wakey-linux"]
exclude = ["vendor/vt100"]
[workspace.dependencies]
anyhow = "1"
macaddr = { version = "1", features = ["serde", "serde_std"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = [
"fs",
"process",
"rt-multi-thread",
"io-util",
"macros",
"time",
] }
tracing = "0.1"
uuid = { version = "1", features = ["v4"] }
[dependencies.lda-ipjs]
path = "ipjs"
registry = "gitea"
version = "0"
[dependencies.wakey-core]
path = "wakey-core"
registry = "gitea"
version = "0"
[dependencies.wakey-linux]
path = "wakey-linux"
registry = "gitea"
version = "0"
+423 -12
View File
@@ -1,20 +1,431 @@
# wakey
router shit
`wakey` is a Wake-on-LAN and LAN-observability tool for a Linux router.
## usage
It started as a small web UI running on-device. It is now being reshaped into a
service-first project with:
- Build (Windows host OK):
- cargo build --release --target armv7-unknown-linux-musleabihf
- Run on a Linux box/router:
- copy target/armv7-unknown-linux-musleabihf/release/wakey to the device
- chmod +x wakey && ./wakey
- Install via release asset (OpenWrt):
- wget -O- `https://your.gitea/owner/repo/releases/download/vX.Y.Z/wakey-rootfs-vX.Y.Z-armv7-unknown-linux-musleabihf.tgz` | tar -xz -C /
- /etc/init.d/wakey enable && /etc/init.d/wakey start
- a reusable core model
- a Linux/OpenWrt adapter layer
- a CLI for operators
- an outbound agent plus control-plane model
Optional updater (fetch latest automatically on OpenWrt):
## What it does
`wakey` currently focuses on a small set of router-side jobs:
- inspect LAN neighbor state
- read DHCP lease data
- merge those facts into a higher-level device inventory
- list useful interface/broadcast information
- send Wake-on-LAN packets
In practice that means commands like:
```sh
WAKEY_HOST=git.ldlda.com WAKEY_OWNER=lda WAKEY_REPO=wakey sh /etc/ldlda_help/update_wakey.sh
wakey inventory bedroom-pc
wakey leases --include-state
wakey devs
wakey wake bedroom-pc
wakey wake --mac aa:bb:cc:dd:ee:ff
```
(`inventory` is the canonical subcommand; `status` is a visible alias for the same behavior.)
## Architecture at a glance
- **On-router (local):** run `wakey` for `inventory`, `leases`, `devs`, and `wake` against live Linux neighbor/DHCP/interface data.
- **Fleet (remote):** `wakey-agent` on each router enrolls with `wakey-control-plane`, keeps an authenticated WebSocket, and executes relayed commands using the same service logic as the local CLI.
## Workspace layout
- `wakey-core`
- shared types and parsing
- device, neighbor, DHCP, interface, and wake models
- `wakey-linux`
- Linux/OpenWrt adapter
- DHCP lease loading, interface summaries, neighbor lookup, WoL sending
- `wakey`
- service layer and operator CLI
- `wakey-agent`
- outbound router daemon, enrollment, websocket command execution
- `wakey-control-plane`
- enrollment endpoint, connected-agent registry, command relay API
- `ipjs`
- typed wrappers around Linux `ip -j ...` data
- JSON-first, with optional experimental netlink backends
## Current architecture
Inside the `wakey` crate:
- `src/service`
- the real use-case layer
- inventory, leases, interfaces, wake, and query resolution
The long-term direction is:
- keep the service layer stable
- keep the local CLI stable for operators
- run remote control via outbound agent + control-plane relay
## Future direction
The project now uses:
- `wakey` for local operator workflows and shared service behavior
- `wakey-agent` for outbound enrollment and websocket execution
- `wakey-control-plane` for enrollment, registry, and command relay
## Logging and troubleshooting
Both daemons emit structured tracing logs to stderr. If you are not seeing
enrollment/command activity, run with increased verbosity.
Control-plane also supports a config file at
`/etc/wakey-control-plane/config.toml` (override with `--config-file`) so you
can persist telemetry settings instead of passing flags.
You can scaffold this file with:
```sh
wakey-control-plane init-config
```
Or bootstrap once during serve (writes only if config is missing):
```sh
wakey-control-plane serve --bootstrap-config
```
Inspect current persisted state:
```sh
wakey-control-plane state-stats
```
List/revoke enroll tokens from CLI:
```sh
wakey-control-plane list-enroll-tokens
wakey-control-plane revoke-enroll-token --token enr-...
wakey-control-plane revoke-agent --agent-id agent-...
```
Machine-readable output is available:
```sh
wakey-control-plane list-enroll-tokens --json
wakey-control-plane state-stats --json
```
Example:
```toml
data_dir = "/var/lib/wakey-control-plane"
bind = "0.0.0.0:8080"
public_url = "https://cp.example.com"
state_file = "state.sqlite3"
pid_file = "wakey-control-plane.pid"
ui_dist_dir = "/opt/wakey/ui/dist"
command_timeout_ms = 30000
enroll_token_ttl_seconds = 86400
[telemetry]
otlp_endpoint = "http://127.0.0.1:4317"
service_name = "wakey-control-plane"
json_logs = false
```
If `telemetry.otlp_endpoint` is omitted, logs still work normally and only local
structured logs are emitted.
State is persisted in an embedded SQLite database (default
`/var/lib/wakey-control-plane/state.sqlite3`).
Relative paths in config are resolved under `data_dir`.
Legacy sled state can be imported explicitly:
```sh
wakey-control-plane migrate-sqlite-state --from /var/lib/wakey-control-plane/legacy.sqlite3 --to /var/lib/wakey-control-plane/state.sqlite3
```
Enroll tokens are now expiring and revocable. Issuance returns `expires_at_unix`.
Expired tokens are rejected on enroll and can be garbage-collected periodically
or on demand.
### Quick start
Control-plane:
```sh
wakey-control-plane -v serve --bind 0.0.0.0:8787 --public-url https://cp.example.com
```
Agent:
```sh
wakey-agent -v serve --config /etc/wakey-agent/config.toml
```
### Fine-grained log filters
Use `RUST_LOG` when you want to focus on websocket/API internals.
```sh
RUST_LOG=wakey_control_plane=debug,wakey_agent=debug wakey-control-plane serve
RUST_LOG=wakey_agent=debug wakey-agent serve
```
### What you should see
During registration/enroll:
- control-plane: `issued enroll token`, then `agent enrollment accepted`
- agent: `starting agent enrollment`, then `agent enrollment succeeded and config was written`
During live connectivity:
- control-plane: `agent websocket upgraded`, `agent authenticated`, `agent disconnected`
- agent: `connecting agent websocket`, `agent websocket dns resolved`, `agent websocket connected`, `agent websocket session authenticated`, `heartbeat sent` (debug)
During command relay:
- control-plane: `dispatching command to agent`
- agent: `received command from control-plane`, then `command execution completed` (or `command dispatch failed`)
- control-plane: `agent command completed` (or timeout/error warnings)
During daemon control/state operations:
- control-plane: `wrote control-plane pid file`, `saved control-plane store`, `reloaded control-plane store from disk`
- agent: `wrote wakey-agent pid file`, `sending wakey-agent reload signal`
Control-plane admin API includes token management endpoints:
- `POST /api/v1/control/enroll-token?ttl_seconds=<n>`
- `GET /api/v1/control/enroll-tokens`
- `DELETE /api/v1/control/enroll-tokens/{token}`
- `GET /api/v1/control/audit/events?agent_id=<id>&event_type=<type>&limit=<n>`
- `GET /api/v1/control/alerts?lookback_seconds=900`
- `GET /api/v1/control/alerts/history?since_unix=<ts>&limit=<n>`
- `GET /api/v1/control/alerts/ws` (websocket snapshots, recent transitions, and evaluator health)
- `GET /api/v1/control/terminals/events/ws` (websocket session-list invalidations)
- `DELETE /api/v1/control/agents/{agent_id}`
- `PATCH /api/v1/control/agents/{agent_id}/nickname`
Alert evaluation runs once per control plane every five seconds. The alerts GET
returns `503 alerts_unavailable` until a successful evaluation, after evaluation
failure, or when its snapshot is stale. The existing alerts stream also sends
`alerts_health` messages with `available` and an optional `reason`; the UI keeps
the last results visible with a stale warning until recovery. Custom alert-rule
query overrides are rejected with `400 unsupported_alert_override`.
Terminal session events carry only `sessions_changed` invalidations. Clients
refetch the session list after changes or reconnection and retain a 15-second
fallback refresh. Events do not grant session ownership; attachment still uses
the existing server-side locking and scoped credentials.
If commands still appear silent, verify both processes are running with `-v`
and that `RUST_LOG` is not overriding to a stricter level.
If websocket connect feels delayed, compare `dns_resolve_ms` and `ws_connect_ms`
from agent logs. Slow DNS is a common source of multi-second connection stalls
when using hostnames; using a stable IP or local host mapping can avoid this.
## Edge Exposure (Caddy + Cloudflare Access)
Control-plane is intended to run behind a reverse proxy with TLS termination.
Use Cloudflare Access to protect `/ui/*` and `/api/v1/control/*`, while keeping
agent enrollment and websocket endpoints reachable.
An example Caddy config is provided at:
- `deploy/control-plane.Caddyfile`
Expected exposure model:
- Public: `/healthz`, `/api/v1/agents/enroll`, `/api/v1/agent/ws`
- Private (Cloudflare Access): `/ui/*`, `/api/v1/control/*`
Control-plane routing is organized with the same boundary in code:
- public router: health, enroll, agent websocket
- control router: all `/api/v1/control/*` admin endpoints
This keeps edge policy and app routing aligned as features grow.
## UI (Initial Shell)
Control-plane serves the built Operator UI at `/ui/` from `ui_dist_dir`
(defaults to `ui/dist`). Configure this in
`/etc/wakey-control-plane/config.toml` or pass `--ui-dist-dir` to `serve`.
Build UI assets before starting control-plane:
```sh
cd ui
pnpm install
pnpm build
```
Then start control-plane and open `/ui/` on the same host/port.
## VPS Deploy (Manual Updates)
Suggested layout on VPS:
- `/opt/wakey/bin/wakey-control-plane`
- `/opt/wakey/ui/dist/*`
- `/etc/wakey-control-plane/config.toml` with `ui_dist_dir = "/opt/wakey/ui/dist"`
Use the provided unit template:
- `deploy/systemd/wakey-cc.service`
Install on VPS:
```sh
sudo install -m 0644 deploy/systemd/wakey-cc.service /etc/systemd/system/wakey-cc.service
sudo systemctl daemon-reload
sudo systemctl enable --now wakey-cc.service
```
Manual update helper for VPS:
```sh
chmod +x scripts/update_wakey_cc.sh
cd /opt/wakey
sudo -E ./scripts/update_wakey_cc.sh
# optional: pin target and/or version
WAKEY_CC_TARGET=x86_64-unknown-linux-gnu sudo -E ./scripts/update_wakey_cc.sh
WAKEY_CC_VERSION=v0.2.0 WAKEY_CC_TARGET=x86_64-unknown-linux-gnu sudo -E ./scripts/update_wakey_cc.sh
```
The update tarball is expected to contain:
- `bin/wakey-control-plane`
- `ui/dist/index.html` (plus `ui/dist/assets/*`)
## CLI
`wakey` is usable as a local/operator CLI.
### Inventory
Show merged device inventory rows using a free-form selector:
```sh
wakey inventory bedroom-pc
```
Or use explicit filters:
```sh
wakey inventory --dev br-lan --nud reachable
wakey inventory --mac aa:bb:cc:dd:ee:ff
wakey inventory --json
```
The `status` subcommand is an alias for `inventory` (same flags and output).
### Leases
Show DHCP leases:
```sh
wakey leases
wakey leases --include-state
wakey leases --include-state --json
```
### Wake
Query mode:
```sh
wakey wake bedroom-pc
```
Explicit/manual mode:
```sh
wakey wake --mac aa:bb:cc:dd:ee:ff
wakey wake --mac aa:bb:cc:dd:ee:ff --ip 192.168.1.255
wakey wake --mac aa:bb:cc:dd:ee:ff --json
```
Rules:
- query mode and explicit `--mac/--ip` mode are mutually exclusive
- `--ip` requires `--mac`
- `--mac` without `--ip` fans out to interface broadcast targets
### Interfaces
Show condensed interface summaries:
```sh
wakey devs
wakey devs br-lan
wakey devs --up
wakey devs --json
```
## Tests
This repo has two useful testing modes:
- local compile checks
- live on-device tests against the real router/runtime environment
### Local
```sh
cargo check
cargo test --no-run
cargo clippy --all-targets --all-features -- -D warnings
```
On GitHub Actions (`.github/workflows/ci.yml`), the same Rust checks run on
`ubuntu-latest`, plus a separate **`ui`** job: `pnpm install --frozen-lockfile`
in `ui/`, then `typecheck`, `format:check`, and `vite build`.
Focused control-plane state tests:
```sh
cargo test -p wakey-control-plane state::store::tests::gc_removes_expired_tokens
cargo test -p wakey-control-plane state::store::tests::enroll_rejects_expired_token
cargo test -p wakey-control-plane state::store::tests::stats_counts_agents_and_expired_tokens
```
### On-device
Some integration tests are intentionally `#[ignore]` because they use real
router state. Use the PowerShell helper:
```powershell
./scripts/test_remote.ps1 -Package wakey -BinaryFilter integration_live_services -Ignored -NoCapture
./scripts/test_remote.ps1 -Package wakey -BinaryFilter integration_inventory -Ignored -NoCapture
```
You can further narrow execution with `-Filter` to select individual Rust test
functions inside a test binary.
## Build target
This project is primarily aimed at an OpenWrt/Linux ARM router target. The
workspace is commonly built for:
```text
armv7-unknown-linux-musleabihf
```
Some crates and tests are Linux-specific by design.
## Notes
- `ipjs` is JSON-first by default; experimental netlink paths exist where they
are worth keeping.
- the current web client is temporary and kept alive through explicit
compatibility mapping
- the service layer is the part intended to survive the migration
+32
View File
@@ -0,0 +1,32 @@
# Caddy template for wakey-control-plane with Cloudflare Access.
#
# Security model:
# - Public endpoints for agents: health, enrollment, control WS, and scoped terminal relay WS
# - Private admin surface: root, /ui/* and /api/v1/control/* (verified Access JWT)
# Configure CC's [access] section and loopback bind before enabling this template.
# Never expose /internal/auth/verify through this virtual host.
#
# Replace wakey.ldlda.com and the loopback upstream port for your deployment.
wakey.ldlda.com {
encode zstd gzip
# Public agent-facing endpoints.
@public path /healthz /api/v1/agents/enroll /api/v1/agent/ws /api/v1/agent/terminals/*
handle @public {
reverse_proxy 127.0.0.1:6767
}
# Applies to HTTP requests and operator WebSocket upgrades, not WS frames.
@admin path / /ui* /api/v1/control/*
handle @admin {
forward_auth 127.0.0.1:6767 {
uri /internal/auth/verify
}
reverse_proxy 127.0.0.1:6767
}
# Deny unknown paths by default.
respond "not found" 404
}
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=Wakey Control Plane
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=lda
Group=lda
WorkingDirectory=/opt/wakey
ExecStart=/opt/wakey/bin/wakey-control-plane serve --config-file /etc/wakey-control-plane/config.toml
Restart=on-failure
RestartSec=2
Environment=RUST_LOG=info
EnvironmentFile=-/etc/wakey-control-plane/environment
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,164 @@
# Core Endpoints and Wake Routes
Wakey will model observed network contact points as **Endpoints** in `wakey-core`, and derive **Wake Routes** from those endpoints instead of reconstructing routes from flattened device summary MAC/IP arrays. `Device.ips` and `Device.macs` remain true summary fields for operator display and compatibility, but endpoint data is authoritative for wake, freshness, source, per-IP state, and route selection.
**Status**: accepted
## Context
The previous model stored a `Device` aggregate with summary `macs`, `ips`, `presence`, and raw observation facts. The control plane then built fleet wake routes from combinations like first MAC plus first IP. That lost source, presence, interface, and MAC/IP-pair evidence, especially when hook memory contained removed IPs or when several sources described the same address differently.
## Decision
Add a typed `DeviceEndpoint` concept in `wakey-core`. A device snapshot sent by an agent contains devices with endpoints already attached. The control plane stores structured endpoint rows and derives fleet summaries and wake routes from those rows.
Endpoint shape:
```rust
DeviceEndpoint {
key: EndpointKey,
hostname: Option<String>,
interface: Option<String>,
presence: Presence,
first_seen_unix: Option<u64>,
last_seen_unix: Option<u64>,
}
EndpointKey {
source: EndpointSource,
mac: Option<MacAddr>,
ip: Option<IpAddr>,
}
AgentEndpointKey {
agent_id: String,
endpoint: EndpointKey,
}
```
`EndpointKey` must contain at least one of MAC or IP. Hostname and interface are endpoint evidence/metadata, not identity. `AgentEndpointKey` may use `serde(flatten)` for wire shape, but hash values are never durable storage keys. String keys are boundary serialization only.
## Source and Presence Rules
Endpoint sources are typed domain variants, not free strings:
```text
Neighbor
DhcpLease
HookNeighbor
HookDhcp
```
Presence answers “is this reachable?”, not “can this be woken?” The presence order is:
```text
Unknown < Offline < LikelyOnline < Online
```
Source mapping:
```text
Neighbor reachable/permanent -> Online
Neighbor stale -> LikelyOnline
Neighbor failed/remove-like evidence -> Offline
Other neighbor states -> Unknown
Current DHCP lease -> Unknown
Hook DHCP add/update/remove -> Unknown
Hook neighbor add/update/old -> LikelyOnline
Hook neighbor remove -> Offline
```
Current DHCP leases are summary-eligible and may support wake if they include a MAC, but they do not prove reachability. Hook memory creates endpoints and observation facts, but does not directly inflate summary IPs.
## Summary, Presence, and UI
`Device.ips` and `Device.macs` stay as summaries. Summary IPs come from concrete live-ish sources such as current neighbor rows and current DHCP lease rows. Hook-derived and offline IPs remain visible through endpoints but are collapsed out of primary UI summaries by default.
Fleet display labels prefer the saved device name, then a hostname, then a MAC,
then an IP. Generated address labels use `Device: <address>` without presence
prefixes; the badge carries presence. An inactive IP is only a naming fallback
when no name or MAC exists, never evidence of a current address or a wake route.
Offline neighbor evidence does not establish that a DHCP address has expired or
been reassigned. If a concrete source observes that endpoint again, its eligible
IP returns to the summary; manually remembered identifiers are not removed by this.
`Device.presence` is derived from all endpoints, not only summary-eligible endpoints. This lets concrete offline evidence matter while allowing stronger live evidence to override it.
The control plane derives stored snapshot presence and fleet presence from the
maximum endpoint signal whenever endpoints exist. A cached summary must not
override endpoint evidence; endpoint-less legacy rows fall back to their stored
summary. Presence describes the last observation, not guaranteed current
reachability. Agent disconnection does not rewrite endpoint presence or expire
the retained snapshot.
The main fleet API embeds endpoints inside each fleet device. API responses expose all endpoints, including offline and unknown endpoints. The UI may collapse offline/unknown endpoints in the primary row, but details must expose them for copy/debug/history.
## Wakeability and Wake Route Ordering
Wakeability is derived, not stored on `DeviceEndpoint`.
An endpoint is wakeable when:
```text
endpoint has a MAC
agent is connected
agent has wake capability
endpoint source is allowed for wake route derivation
```
For now, a connected wakey-agent is assumed to have wake capability. Presence does not gate wakeability: an `Offline` endpoint may still produce a wake route, because waking powered-off devices is the core use case.
Preferred wake route order:
```text
connected agent
wakeable route
has IP
presence quality
newest last_seen
source quality
```
Presence quality for route ranking follows:
```text
Online > LikelyOnline > Offline > Unknown
```
Source quality follows:
```text
Neighbor > DhcpLease > HookNeighbor > HookDhcp
```
Equivalent wake routes may ignore endpoint source when they target the same agent, MAC, and IP. Endpoint evidence preserves source-specific rows; route grouping may deduplicate equivalent targets.
## Device and Identity Rules
`DeviceId` remains the typed observed identity enum:
```rust
DeviceId::Mac(MacAddr)
DeviceId::Ip(IpAddr)
```
`DeviceId` is derived from endpoints: canonical MAC if any endpoint has a MAC, otherwise canonical IP, otherwise absent. Local source rows are grouped into devices by endpoint-derived `DeviceId`, not exact `EndpointKey`.
Within a single complete local snapshot, a MAC+IP endpoint may absorb an IP-only endpoint with the same IP. This merge is not remembered across snapshots unless the operator creates a known-device identifier.
Known-device identifiers are source-independent ownership claims over MAC or permanent IP values. Wakey does not infer whether an IP is permanent, static, or reserved; the UI should warn the operator when attaching an IP identifier.
## Control Plane Storage
The control plane stores current per-agent endpoint snapshots as structured columns, not opaque `Device` JSON and not endpoint event history. Summary MAC/IP collections are derived from endpoints; separate MAC/IP storage should be removed or represented as views rather than maintained as independent truth.
Agent-local hook memory is retained by local last-seen age policy, not by control-plane acknowledgement. The default retention is 7 days unless configured otherwise. Live-source endpoints use snapshot time as their observed time; hook-derived endpoints use the hook row's recorded last-seen time.
## Consequences
- Wake route construction moves away from `macs.first()` / `ips.first()` guessing.
- The agent/core layer owns source interpretation because it still has local context.
- The control plane can search, filter, match known identifiers, and rank wake routes from structured endpoint rows.
- UI can show clean summaries while keeping complete endpoint evidence in details.
- This preserves “wake an offline machine by MAC” without pretending that offline means not wakeable.
+155
View File
@@ -0,0 +1,155 @@
# Remote Terminal Sessions
Wakey will provide opt-in remote terminal access by pairing a browser terminal WebSocket with a dedicated outbound agent terminal WebSocket. The existing agent WebSocket remains the control channel and does not carry terminal byte streams.
**Status**: accepted
## Context
The control plane already maintains an authenticated outbound WebSocket from each connected agent. Its command protocol is intentionally request/result shaped: the control plane sends one command, the agent executes it, and one result completes the pending request.
An interactive terminal has different semantics. It is long-lived, bidirectional, byte-oriented, and must handle window resizing, process exit, disconnect cleanup, and backpressure. Treating it as an ordinary command would either block the agent session loop or turn the main agent WebSocket into a general stream multiplexer. It would also allow terminal output to compete with heartbeats, snapshots, and wake commands.
Agents commonly run behind NAT and must not expose an inbound listener. Terminal connections therefore remain agent-initiated and outbound.
## Decision
Use one dedicated agent WebSocket and one dedicated operator WebSocket for each terminal session. The control plane holds an in-memory terminal relay that pairs those sockets.
Session establishment follows this sequence:
1. An authenticated operator requests a terminal for a connected, terminal-capable agent.
2. The control plane creates an ephemeral terminal ID plus short-lived, single-use attachment credentials.
3. The control plane sends an open-terminal control message over the existing authenticated agent WebSocket.
4. The agent opens a new outbound terminal WebSocket to the control plane and authenticates it for that terminal ID.
5. The browser opens the corresponding protected operator terminal WebSocket.
6. The control plane pairs the sockets and relays terminal frames while an operator is attached.
The main agent WebSocket carries terminal creation and cancellation control only. It does not carry PTY input or output.
## PTY Ownership
The agent owns the PTY, shell process, process group, and all process cleanup. The control plane never spawns or emulates a shell.
Use `pty-process` with its async feature as the initial PTY abstraction because it provides:
- Tokio `AsyncRead` and `AsyncWrite` integration;
- owned read and write halves for concurrent tasks;
- terminal resizing;
- child session-leader and controlling-terminal setup; and
- a small implementation built on `rustix`.
The PTY wrapper is cross-compiled for `armv7-unknown-linux-musleabihf` and its input, output, resize, and exit test has passed on the target router. That focused test remains part of the remote compatibility workflow. Wakey does not call `forkpty` or add its own unsafe PTY implementation.
The executable, working directory, environment, UID, and GID are agent-controlled configuration. The browser cannot supply an arbitrary executable or process environment.
## Wire Protocol
WebSocket frame type separates terminal data from terminal control:
- Binary frames carry raw PTY input and output bytes.
- Text JSON frames carry lifecycle, error, and resize messages.
The terminal control vocabulary is deliberately small:
```text
operator -> agent: resize, close
control plane -> agent: snapshot
agent -> operator: ready, exited, error
```
Initial terminal dimensions are part of session attachment. Resize carries rows and columns; pixel dimensions may be added later if a demonstrated program requires them.
Terminal behavior such as Ctrl-C, Ctrl-Z, Ctrl-D, cursor keys, mouse reporting, bracketed paste, colors, and terminal-title changes remains in the byte stream. The control plane does not parse ANSI escape sequences. The browser terminal emulator renders output and owns connected-session scrollback. The agent also feeds PTY output into a `vt100` parser so it can reconstruct the current visible screen and terminal input modes after detachment. Agent PTYs advertise `TERM=xterm-256color` and `COLORTERM=truecolor` because xterm.js is the actual frontend; applications may therefore negotiate xterm mouse reporting without a Wakey-specific mouse protocol.
WebSockets already provide ordered, reliable delivery, so terminal frames do not carry sequence numbers in the initial protocol.
## Lifecycle and Cleanup
Terminal sessions allow only one attached operator. Their lifetime belongs to the agent process, not to a browser route or a particular control-plane connection.
When the operator socket disconnects, the session becomes detached. Navigation, browser closure, and network loss do not terminate the PTY. A protected operator request may discover the live session and obtain a fresh, single-use attachment credential. The control plane does not retain terminal output.
The operator UI lists live sessions as tabs and stores only the active terminal ID in browser-tab-scoped `sessionStorage`. On reload it prefers that ID and briefly waits for the previous WebSocket to detach before requesting a fresh attachment credential. The stored ID is a navigation hint, not an ownership credential; another attached operator still locks the session at the control plane.
The protected `/api/v1/control/terminals/events/ws` stream sends `sessions_changed` invalidations when the volatile session catalog or attachment ownership changes. These events contain no terminal bytes or attachment credentials: browsers refetch the ordinary session list, coalescing bursts and repeating a fetch if another event arrives during it. Subscribing and reconnecting also invalidate the list. The 15-second refresh remains a recovery fallback; the stream is a freshness hint, never an authorization or locking mechanism.
The React page composes three custom hooks rather than owning every resource itself. `useXterm` owns the single renderer, its addons, fitting, fonts, and display operations. `useTerminalSessions` owns the catalog subscription, coalesced refreshes, and fallback timer. `useTerminalSession` owns active attachment, input, restoration, and session operations. The attachment hook waits for renderer readiness; stable renderer operations prevent ordinary state updates from rebuilding the terminal or reconnecting its transport. Each hook cleans up its own resources on unmount, which detaches the browser without deleting the agent-owned PTY.
After operator attachment, the control plane sends a `snapshot` request. The agent serializes up to 1,000 retained physical rows followed by its parsed current screen and input modes as terminal escape bytes, sends them before subsequent live output, and then signals the PTY's current foreground process group with `SIGWINCH`. Historical rows retain their terminal attributes and are replayed as ordinary terminal output so xterm builds its native scrollback; the final formatted state restores the exact live screen. The signal lets full-screen applications redraw without assuming that the original shell remains in the foreground. Signal failure is logged but never terminates the session. The connected browser independently retains up to 10,000 rows because that memory belongs to the operator device rather than the agent host.
Wakey carries a small, read-only extension to `vt100` because its public API exposes only the active grid. A snapshot streams bounded history from the primary grid, redraws that grid with its saved cursor and attributes, and then reconstructs the alternate grid when a full-screen application is active. The parser is never resized or switched while taking a snapshot. Consequently, reconnecting during `btop` restores the application while preserving the hidden shell history and state that reappear when it exits.
The agent keeps its terminal manager outside the control-WebSocket reconnect loop. If a dedicated terminal relay disconnects, the PTY continues draining output into the agent-owned terminal parser while waiting for replacement relay credentials. On every authenticated control connection, the agent reports its in-memory live terminal IDs and creation times. The control plane reconciles that inventory, adopts sessions missing from its volatile registry, and issues fresh relay credentials. This allows sessions to survive control-plane restart without persisting terminal state in SQLite.
Closing a session must terminate the entire PTY process group, not only the shell process. Cleanup should send a hangup first, then escalate to termination and forced kill after bounded grace periods. Explicit operator close, absolute session timeout, agent process exit, and machine reboot close the session.
The agent configuration sets `terminal.session_ttl` (for example, `"12h"`) for newly created PTYs. The default is 12 hours; `"0s"` disables automatic expiry. Legacy `session_ttl_seconds` is accepted with a deprecation warning. The wire protocol still uses integer seconds, so fractional-second TTLs are rejected. The agent owns and enforces this deadline locally because PTYs survive browser and control-plane disconnection. It advertises the policy to the control plane and includes the creation-time TTL in terminal inventory, allowing CC to mirror expiry and preserve it across CC restart. Missing fields from older agents retain the 12-hour default. Positive values are exact and values that cannot fit the platform timer are rejected rather than clamped.
An agent process restart or machine reboot still ends every terminal session because PTY file descriptors cannot be recovered by a new process. Surviving that boundary would require an external session host such as `tmux` or a separate terminal daemon and is not part of this design.
The agent reports a normal exit status or terminating signal when available. The UI must distinguish an exited shell from a transport failure.
## Backpressure and Resource Limits
Terminal transport must not use unbounded queues.
Every queue between PTY, agent socket, control-plane relay, and browser socket is bounded. The agent keeps draining and parsing the PTY while detached so a noisy child cannot stall the agent. Parsed state is bounded by the configured terminal dimensions and a 1,000-row reconnect scrollback limit. The control plane retains only a bounded queue of operator controls while an agent relay is reconnecting.
While a relay is attached, saturation applies lossless backpressure instead of dropping terminal bytes or disconnecting the relay. The agent retains the frame that discovered saturation and pauses further PTY reads until bounded relay capacity returns. Input, resize, close, lifecycle, and reconnect handling remain active while output is backpressured. Reconnect snapshots use the same ordered output path and duplicate snapshot requests are coalesced while one is pending. This is required for terminal protocols such as sixel, where dropping one output frame corrupts the rest of the stream.
When input/control and output are ready simultaneously, relay loops prioritize input and control. This keeps interrupt, resize, close, and snapshot traffic responsive while commands produce sustained output.
The implementation also enforces:
- maximum terminal frame size;
- per-agent concurrent-session limits;
- idle and absolute session timeouts;
- bounded parsed terminal state;
- bounded control-plane relay buffers; and
- cleanup when any relay task exits unexpectedly.
Exact limits are configuration and may be tuned from router testing. The bounded behavior is an architectural requirement.
## Security and Audit
Remote terminal access is root-equivalent on agents that run as root. It is therefore an explicit agent capability and is disabled by default.
Operator terminal endpoints belong to the protected control API surface. Session identifiers are not credentials. Agent and operator attachment credentials are short-lived, scoped to one terminal session, and single-use. The operator WebSocket must enforce the same-origin/protected-control assumptions used when the session was created.
Audit records include terminal request, open, ready, disconnect, close, timeout, and exit metadata. Wakey never stores or audits terminal input, terminal output, command history, or scrollback.
Terminal capability and session state are separate from device inventory, known-device identity, wake routes, and the debug Command Runner.
## Deferred Work
Persistence across agent restart or machine reboot is not supported. A later design would need an external process owner, reconnectable local IPC, and explicit secret handling; persisted metadata alone cannot recover a PTY.
File transfer, multi-operator attachment, terminal recording, shell-history storage, and arbitrary process launch are also deferred.
## Alternatives Considered
### Multiplex terminal bytes over the main agent WebSocket
Rejected for the initial version. It requires refactoring the current request/result session into a general concurrent writer and stream router, adds head-of-line coupling with fleet traffic, and requires terminal-byte framing within a shared connection.
### Model a terminal as a long-running agent command
Rejected. Commands have one result and a timeout; terminals have continuous bidirectional traffic and independent lifecycle.
### Accept an inbound connection on the agent
Rejected. Agents run behind NAT and should not expose a new network service.
### Use `portable-pty`
Viable, but not selected initially. Its cross-platform abstraction is broader than the Linux agent requires and its reader/writer API would need blocking-task bridges. It remains a fallback if `pty-process` does not build or behave correctly on the target router.
## Consequences
- Each active terminal consumes two additional WebSockets and one PTY process on the agent.
- Terminal traffic cannot delay main agent heartbeat, snapshot, or command messages.
- Control-plane terminal state remains ephemeral; agents rebuild it from their in-memory live-session inventory after a control-plane restart.
- The agent session protocol gains terminal-open control and capability advertisement but does not become a terminal-data multiplexer.
- Browser and agent terminal transports can be tested independently before adding xterm.js.
- Browser navigation and control-plane restart do not terminate an agent-owned PTY.
+88
View File
@@ -0,0 +1,88 @@
# Configuration Durations
Agent and control-plane TOML duration settings use strings with explicit units.
Runtime code receives `std::time::Duration`; API and WebSocket numeric fields
such as `timeout_ms`, `session_ttl_seconds`, and `latency_ms` are unchanged.
## Agent
```toml
reconnect_base = "1s"
reconnect_max = "30s"
observation_sync_interval = "60s"
observation_retention = "7d"
[terminal]
session_ttl = "12h"
```
`observation_retention` prunes the agent's local hotplug memory during inventory
collection. It does not delete the control plane's last snapshot for an agent.
`"0d"` disables this local pruning. `terminal.session_ttl = "0s"` disables PTY
expiry. Reconnect and sync timers must be positive and fit the platform timer.
Terminal TTL and hook retention must resolve to whole seconds because their
protocol/storage timestamps use seconds. Reconnect and sync intervals can use
subsecond values.
Reconnect scheduling retains its existing 100ms minimum backoff.
## Control Plane
```toml
command_timeout = "30s"
enroll_token_ttl = "1d"
history_retention = "30d"
device_retention = "60d"
```
`command_timeout`, `enroll_token_ttl`, and `history_retention` must be positive.
Enrollment TTL and history retention must resolve to whole seconds. Command
timeout can use subsecond values.
`history_retention` deletes old audit events and alert transitions, not device
snapshots or saved identities.
`device_retention` expires agent-collected device rows and their child endpoints,
addresses, names and facts. The default is `"60d"`; `"0d"` disables expiry.
It must resolve to whole seconds. Age is measured from the last CC-received
snapshot that included the device, not endpoint timestamps or online presence.
An offline device included in new snapshots therefore stays retained. Saved
devices and their manually attached identifiers are never deleted by this cleanup.
Complete snapshots still remove devices omitted by that agent immediately;
retention handles old rows left behind when an agent stops syncing.
Expired rows are removed by the Unix daemon's existing maintenance loop every
five minutes, including an initial tick at startup. Restart CC to apply changes
to this setting; the state-only reload does not reload configuration.
## Legacy Files
| Old Key | New Key | Numeric Legacy Unit |
| --- | --- | --- |
| Agent `reconnect_base_ms` | `reconnect_base` | milliseconds |
| Agent `reconnect_max_ms` | `reconnect_max` | milliseconds |
| Agent `observation_sync_interval_seconds` | `observation_sync_interval` | seconds |
| Agent `observation_retention_days` | `observation_retention` | days |
| Agent `terminal.session_ttl_seconds` | `terminal.session_ttl` | seconds |
| CC `command_timeout_ms` | `command_timeout` | milliseconds |
| CC `enroll_token_ttl_seconds` | `enroll_token_ttl` | seconds |
| CC `observation_retention_seconds` | `history_retention` | seconds |
Old keys accept non-negative integers in their original units, or explicit
duration strings, and produce a warning on stderr when loaded. New keys require
strings; bare numbers are rejected. Supplying both keys for the same setting is
an error, even when their values agree. Negative, malformed, and overflowing
values are rejected; zero active timers are rejected rather than silently
clamped. No secrets are included in deprecation warnings.
`init-config --from-config ...` reads legacy files and writes only canonical
keys and formatted duration strings. Existing numeric CLI flags are unchanged
in this slice, and their overrides also serialize in the new format.
For example, legacy `reconnect_base_ms = 1500` is read as 1500 milliseconds
and written back as `reconnect_base = "1s 500ms"`. New-key
`reconnect_base = 1500` is rejected: no implicit numeric unit is assigned.
Serialization always writes duration strings, regardless of the accepted input
format, using `humantime-serde`.
The parser is [humantime](https://docs.rs/humantime/latest/humantime/fn.parse_duration.html).
Examples include `"14d"`, `"168h"`, `"250ms"`, and `"1h 30m"`. These are elapsed
durations, not calendar scheduling rules; use days/hours for retention rather
than assuming calendar-month semantics.
+54
View File
@@ -0,0 +1,54 @@
# Fleet View Cache
CC retains one complete, grouped fleet view in memory. List requests still apply
their own search, visibility, presence, agent filters and result limit. Neither
the database nor the response format changes.
## Inputs And Invalidation
The cache key combines the store's fleet revision and connected-agent IDs.
Successful snapshot writes, saved-device create/rename/forget/merge, identifier
edits, agent enrollment/revocation/nickname edits, and device-retention cleanup
advance the revision. Token-only, audit and alert writes do not invalidate it.
Connection changes are detected from the live session map on each read.
The next reader rebuilds a changed view. Concurrent readers wait for that build
and reuse it. The helper checks the key again after building: if inputs changed
while database reads/grouping were in flight, it discards the result and retries.
Build errors are returned, not cached; cancelling a reader releases the lock.
The previous view is not served as a fallback after a rebuild error.
After three invalidated builds, the reader stops and releases the lock. Fleet
list/wake requests return HTTP 503 with code `fleet_busy`; clients can retry
later. No stale view or command is used as a fallback. This bounds the number
of rebuilds per reader, not database execution time or total concurrent requests.
Wake searches the complete cached view by device key, without list visibility
filters or the list API's 1,000-row limit. It borrows the view and clones only the
selected route. Command dispatch still checks the current session;
a cached route cannot grant access to a disconnected agent.
`GET /api/v1/control/fleet/devices/{device_key}` returns one exact row from the
complete view, or `404 fleet_device_not_found`. Details do not inherit list
filters or limits. After Remember/Attach/Merge, the UI follows the saved ID
returned by the mutation, not matching MAC/IP heuristics. It also refreshes the
full saved identity independently of list results; Forget still closes details.
## External Writes
The revision belongs to the running CC process. If another process directly
modifies its SQLite database, run the existing CC reload command (or send
SIGHUP) to invalidate the view, or restart CC. The cache does not watch files
or poll SQLite for external changes. Normal HTTP/WS store writes invalidate
automatically, and there is no time-based cache expiry.
## Shared Helper And Tracing
`runtime::view_cache::ViewCache` owns synchronization and stale-build rejection.
Fleet code supplies the key and builder. It is intentionally CC-local; alerts
keep their existing timer-driven evaluator rather than being forced into this
lazy cache.
`fleet_load` spans remain on requests. A cache miss adds `fleet_rebuild`, with
database loads and `fleet_group_devices` nested below it. On a cache hit, list
requests clone/filter the view; wake requests look up their device in the borrowed
view. Neither path repeats the database reads or grouping.
+134
View File
@@ -0,0 +1,134 @@
# Multi-CC Identity And Configuration
Status: proposal, 2026-10-12. This is not an implemented config format.
## Goal
One agent process can serve production and test CCs simultaneously. Collect
locally once, forward to independent connections, and show human names alongside
IDs. A failed CC must not block another or kill local terminal processes.
## Identity And Names
- **CC ID:** stable identity of a logical control plane, independent of URL,
hostname, display name and WebSocket connection. Renaming or moving it must
not require agents to enroll again.
- **CC name:** configured on CC and advertised to authenticated agents. Start
with config-based rename plus reload/restart; no rename API required initially.
- **Agent instance ID/name:** local daemon identity and reported human name,
shared across its connections. Not the enrollment identity of every CC.
- **Enrollment:** each CC issues its own `agent_id` and token. Never send one
CC's credentials to another. Existing per-CC agent nicknames override the
reported name in that CC's UI; names never become routing/authentication keys.
- **Connection alias:** local config key such as `cloud` or `test`, useful for
CLI selection and pre-auth logs. It is not the remote CC ID or authoritative
remote name.
CC ID is generated once and retained in SQLite metadata when not configured;
an explicit config ID must agree with an existing stored identity, not silently
replace it. New init-config output can include a generated ID. Agent instance
ID belongs in its local config. Copying either deployment for an independent
test instance requires a distinct identity; do not mint a new ID each startup.
## Proposed Config Shape
CC keeps existing operational settings and adds:
```toml
[identity]
id = "cc-<uuid>"
name = "Cloud"
```
Agent separates local identity/settings from per-CC enrollment:
```toml
[identity]
id = "node-<uuid>"
name = "Router"
[local]
pid_file = "/var/run/wakey-agent.pid"
dhcp_leases_path = "/tmp/dhcp.leases"
mac_name_cache_path = "/tmp/wakey_mac_names.json"
observation_store_path = "/tmp/wakey_observations.json"
[sync]
interval = "60s"
hook_retention = "7d"
[reconnect]
base = "1s"
max = "30s"
[control_planes.cloud]
server_url = "https://wakey.example.com"
agent_id = "agent-<cloud-issued-id>"
agent_token = "<cloud-token>"
# expected_cc_id = "cc-<uuid>"
[control_planes.test]
server_url = "http://127.0.0.1:8080"
agent_id = "agent-<test-issued-id>"
agent_token = "<test-token>"
```
Existing `[terminal]` and `[telemetry]` remain daemon-wide. Reconnect defaults
apply independently to each connection; avoid per-CC copies of every setting.
The field names above are proposed, not a reason to rename unrelated CC settings.
Keep accepting the legacy single-CC root fields as one `default` connection,
with a deprecation warning. Reject mixed legacy/new connection declarations
rather than guessing. Init-config emits the new shape; `--from-config` preserves
all connections and their credentials. Enrollment targets a connection alias:
one connection can be implicit, multiple connections require explicit selection.
## Connection And Forwarding Rules
- Add negotiated, post-auth CC identity/name metadata. Current protocol has
Hello/Auth but no explicit successful-auth response; sending credentials is
not proof of authentication. Old clients must not receive unsupported enum
variants unconditionally. Keep legacy single-CC compatibility explicit.
- Forward the agent's configured name during hello; CC sends its own name/ID
after auth. Show `name (id)` or a short ID in operator/debug views. Retain the
local alias and last reported name for disconnected status, marking it offline.
- Each CC gets its own worker, retry state, bounded outbound queue and request
replies. Reject duplicate authenticated connections to the same CC ID; changed
expected IDs require an explicit operator decision, not silent rebinding.
- CC ID is identification, not a substitute for TLS/server authentication.
- Share local inventory/hook storage and periodic collection. Fan out complete
snapshots under each CC's enrollment ID; a slow connection cannot hold the
collector hostage. This does not turn snapshots into a durable event journal.
- Requests/replies and their trace contexts stay scoped to their connection.
Never broadcast command results or terminal bytes to every CC.
- Saved devices, nicknames, permissions and history remain independent on each
CC. No CC-to-CC synchronization or automatic identity promotion.
## Terminal And Telemetry Scope
The agent owns PTYs and one daemon-wide session registry. Session limits apply
globally, not once per connection. Initially, sessions belong to their creating
CC: another CC cannot attach, resume or close them. Attachment ownership is
enforced on the agent, not just inferred from one CC's registry. Disconnecting
one CC preserves its PTYs until existing TTL/explicit-close/agent-exit policy acts.
Reconnecting the same CC ID can reconcile its own sessions; removing a configured
CC must have an explicit terminal cleanup policy before implementation ships.
Use local agent instance ID and CC ID for `service.instance.id`, addressing the
current unspecified CC instance. Add configured display names as resource
metadata, not a replacement for stable IDs. Grafana presentation/label mapping
needs validation; do not promise names will automatically become `instance`.
CPU/RSS/host metrics describe one local process and must not be duplicated per CC.
Document whether snapshot counters count collections or per-CC sends before fan-out.
## Implementation Order
1. Stable CC/local-agent identities, names, telemetry metadata and config adapters.
2. Negotiated authenticated metadata exchange; keep the one-CC path working.
3. Shared local managers plus isolated connection workers and snapshot fan-out.
4. Global terminal ownership checks and multi-CC operator/debug status.
Acceptance tests must cover config/enrollment isolation, names changing without
IDs changing, one CC failing while another proceeds, shared collection without
cross-CC replies, duplicate CC identity rejection, and cross-CC terminal access
rejection. Use two test CCs and one agent before deploying this on the router.
+178
View File
@@ -0,0 +1,178 @@
# OpenWrt UCI for Wakey
Wakey's OpenWrt init script reads `/etc/config/wakey` for the log filter and
OTLP authorization header, then passes them to the agent through procd.
The agent's application settings remain in `/etc/wakey-agent/config.toml`.
The previous `/etc/wakey-agent/environment` file is no longer read.
## The three names
```sh
uci set wakey.main.otlp_authorization='Basic BASE64_OF_USERNAME_COLON_PASSWORD'
```
| Part | Meaning |
| --- | --- |
| `wakey` | Package: `/etc/config/wakey` |
| `main` | Named section inside that package |
| `otlp_authorization` | Option inside the section |
Quotes keep the complete `Basic ...` value together despite its space.
The credential is the Base64 encoding of `username:password`.
It is not the htpasswd hash, and Base64 is not encryption.
## Create and save
Run as root on the router. `touch` does not truncate an existing file:
```sh
touch /etc/config/wakey
chown root:root /etc/config/wakey
chmod 600 /etc/config/wakey
uci set wakey.main=service
uci set wakey.main.log_filter='info'
uci set wakey.main.otlp_authorization='Basic BASE64_OF_USERNAME_COLON_PASSWORD'
uci commit wakey
chmod 600 /etc/config/wakey
```
`wakey.main=service` creates a named section of type `service`. The type is our
chosen label, not a built-in Wakey feature. Existing options are not cleared.
`set` stages changes; `commit wakey` writes that package to disk. Committing does
not restart a service.
The resulting file looks like:
```text
config service 'main'
option log_filter 'info'
option otlp_authorization 'Basic BASE64_OF_USERNAME_COLON_PASSWORD'
```
The example above uses a placeholder. Avoid typing real credentials into a
command that your shell will save in history. In an interactive SSH terminal, you can
read the Basic header without echoing it and send it to UCI over stdin:
```sh
(
set -e
terminal_state=$(stty -g </dev/tty)
# Restore the original terminal settings even on failure or interruption.
trap 'stty "$terminal_state" </dev/tty' 0
trap 'exit 1' HUP INT TERM
printf 'Complete Basic authorization header: ' >/dev/tty
stty -echo </dev/tty
IFS= read -r authorization </dev/tty
stty "$terminal_state" </dev/tty
printf '\n' >/dev/tty
printf "set wakey.main.otlp_authorization='%s'\ncommit wakey\n" "$authorization" | uci batch
chmod 600 /etc/config/wakey
)
```
Use a normal `Basic <base64>` header here, without quotes/newlines inside the value.
The shell's builtin `printf` avoids passing the secret in `uci`'s command arguments.
UCI is not a secret vault: committed files, staged changes, router backups, and
root access can expose these credentials. Do not paste their output into logs/chat.
## Inspect, change, delete
Inspect the non-secret option:
```sh
uci get wakey.main.log_filter
```
`uci show wakey`, `uci export wakey`, `uci changes wakey`, and
`uci get wakey.main.otlp_authorization` **print the credential**. Use them only
when you deliberately want to see it.
Change an option:
```sh
uci set wakey.main.log_filter='wakey_agent=debug,wakey=debug,opentelemetry=warn'
uci commit wakey
```
Delete just the authorization option:
```sh
uci -q delete wakey.main.otlp_authorization
uci commit wakey
```
If TOML still requires `authorization_env`, removing the variable makes startup
fail. Remove that TOML field too only when the receiver no longer requires auth.
Discard all uncommitted changes to this package:
```sh
uci revert wakey
```
## How the service reads it
`config_load` and `config_get` are shell helpers from `/lib/functions.sh`, available
in the normal `/etc/rc.common` init-script environment. They are not standalone
commands to run directly in your SSH shell.
```sh
config_load wakey
config_get authorization main otlp_authorization
```
`config_get` arguments are **destination variable, section, option, optional default**.
The line above puts the option into the shell variable `authorization`. It does
not export it to the agent automatically; procd must receive it explicitly.
The checked-in [init script](../scripts/init/openwrt/wakey) uses these helpers.
Its configuration handling is:
```sh
start_service() {
local authorization='' log_filter='info'
if [ -f /etc/config/wakey ]; then
config_load wakey || return 1
config_get authorization main otlp_authorization
config_get log_filter main log_filter 'info'
fi
procd_open_instance
procd_set_param command "$BIN" serve --config "$CONFIG"
procd_set_param file "$CONFIG"
[ ! -f /etc/config/wakey ] || procd_append_param file /etc/config/wakey
procd_set_param env "RUST_LOG=$log_filter"
[ -z "$authorization" ] || procd_append_param env "WAKEY_OTLP_AUTHORIZATION=$authorization"
procd_set_param respawn 5 1 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
```
Keep these fields in the agent's TOML:
```toml
[telemetry]
otlp_endpoint = "http://10.5.0.1:4317"
authorization_env = "WAKEY_OTLP_AUTHORIZATION"
```
UCI stores the header; procd passes the environment variable; Rust reads it using
the name in TOML. The application does not parse UCI itself.
After installing the updated init script and committing settings:
```sh
/etc/init.d/wakey restart
```
Use **restart**, not the existing HUP-based reload: a running process cannot receive
changed environment variables that way. UCI is only for the router; the CC's
systemd environment file remains unchanged. See [telemetry.md](telemetry.md).
## References
- [OpenWrt UCI CLI source and command usage](https://github.com/openwrt/uci/blob/master/cli.c)
- [OpenWrt config_load/config_get helpers](https://github.com/openwrt/openwrt/blob/main/package/base-files/files/lib/functions.sh)
+118
View File
@@ -0,0 +1,118 @@
# Origin Authentication With Caddy
Cloudflare Access protects the operator surface at the edge. An origin reachable
directly must also verify Access tokens: a nonempty assertion header is not
authentication. A read-only probe through `mails.ldlda.com`, preserving Wakey's
TLS hostname and HTTP host, returned 403 without a header and 200 with a forged
header on the same origin IP. Do not retain the old header-presence matcher.
## Configure CC
Add this to the deployed CC configuration, using your protected application's
settings, not the bypass application's audience:
```toml
bind = "127.0.0.1:23501"
[access]
issuer = "https://ldlda.cloudflareaccess.com"
audience = "0c8ca0bce40a48ddc5bc065cea8390eaddd75a84458f147bbe249fcc57c3d781"
# Optional; defaults to the issuer's /cdn-cgi/access/certs endpoint.
# jwks_url = "https://ldlda.cloudflareaccess.com/cdn-cgi/access/certs"
```
Issuer and key URLs must use HTTPS without user credentials, query or fragment.
The issuer is an origin without a trailing slash; it must exactly match the JWT
issuer. The audience is not a secret. URLs come only from trusted configuration,
never from an incoming token. `init-config --from-config` preserves `[access]`.
CC requires a loopback bind when `[access]` is configured. With no `[access]`,
the verifier returns 401; existing local development routes remain unchanged.
Changes to Access configuration require a daemon restart, not a state reload.
## Configure Caddy
Use [the Caddy template](../deploy/control-plane.Caddyfile), replacing the domain
and every upstream port with your deployment values. Its protected handler calls
CC's `GET /internal/auth/verify` through `forward_auth`, then proxies the original
request only on success. No additional service or custom Caddy module is needed.
Protect `/`, `/ui*` and `/api/v1/control/*`. This includes operator WebSocket
handshakes; established WebSocket frames are not individually authenticated and
token expiry does not automatically disconnect an existing WebSocket.
Keep `/healthz`, `/api/v1/agents/enroll`, `/api/v1/agent/ws` and
`/api/v1/agent/terminals/*` outside Access verification. They retain Wakey's own
agent/scoped-relay authentication. Cloudflare's bypass application should cover
these paths; terminal child paths must be included. If using HTTP ACME challenges,
ensure `/.well-known/acme-challenge/*` is exempt at Cloudflare; Caddy handles its
own active challenges, not CC.
Do not proxy `/internal/auth/verify` publicly and do not put `forward_auth` in
front of the verifier itself. Do not replace verification with a static header
that Caddy adds to every request. Caddy owns enforcement: direct access to the
CC port would bypass it, so loopback binding and host access controls matter.
## Verification And Cache
The verifier accepts only RS256, verifies signatures, and requires matching
issuer/audience plus expiry. A future `nbf` also rejects the token. No clock-skew
leeway is applied; keep the host clock synchronized. Duplicate assertion headers
and assertions over 16 KiB are rejected. No tokens, claims or upstream bodies
are logged.
Responses have no identity payload:
| Status | Meaning |
| --- | --- |
| 204 | Valid protected-application token |
| 401 | Missing/invalid token, unknown key after successful key retrieval, or unconfigured verifier |
| 503 | Required signing keys cannot be obtained safely |
CC reuses one HTTP client and stores parsed keys with their HTTP cache policy.
`http-cache-semantics` determines freshness from the issuer's `Cache-Control`,
`Age`, `Date` and `Expires`, rather than a built-in key TTL. For example,
`public, max-age=14400, must-revalidate, no-transform` permits four hours of
freshness minus the response's existing age; `must-revalidate` forbids stale
reuse, not every fresh reuse. No heuristic lifetime is invented when freshness
is unspecified. A `no-cache` response requires revalidation before reuse;
`no-store` retains neither keys nor policy after serving the fetching request.
Fresh matching keys verify locally. Stale policies produce conditional requests
using ETag or Last-Modified when available. A matching 304 renews the policy and
reuses parsed keys without downloading/parsing a body; mismatched or unsolicited
304 responses fail closed. An unknown key ID forces conditional revalidation
even when the stored response remains fresh, to discover rotation.
Fetches are single-flight and limited to once per minute, including failures.
Rotation immediately after a fetch may therefore take up to a minute to become
available. If the issuer requires revalidation on every use (or allows no
storage), subsequent callers inside that cooldown receive 503 rather than reuse
keys contrary to the HTTP policy. Successful 200 refresh replaces the entire
set, including removing all keys for a valid empty set. Failed refresh does not
extend freshness: matching keys may be used only while the stored policy still
permits reuse. There is no indefinitely stale fallback, including on outages.
Fetches have a five-second timeout, no redirects, a 256 KiB body limit and at
most 64 keys. These limits are internal safeguards, not new config knobs.
## Rollout
1. Install the new CC binary, add `[access]`, and restart CC. Check the loopback
verifier returns 401 for an absent or forged assertion.
2. Update Caddy from the template and validate its configuration before reload.
The repo template uses port 6767; this deployment uses 23501.
3. Confirm a real Access login can use the UI/control APIs and operator terminal
WebSocket. Confirm agent connections and enrollment still work.
4. Repeat a direct-origin request with Wakey's Host/SNI. Both absent and forged
assertions must return 401, not the UI. Verify the internal endpoint itself
returns 404 through the public virtual host.
Do not roll back to header-only acceptance on a verification failure. A UI
build or a CC restart alone does not update the deployed Caddy policy.
References: [Cloudflare token validation](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/validating-json/)
and [Caddy forward_auth](https://caddyserver.com/docs/caddyfile/directives/forward_auth).
HTTP policy is provided by [http-cache-semantics](https://docs.rs/http-cache-semantics/latest/http_cache_semantics/struct.CachePolicy.html);
only the single-resource storage, bounded fetch and anti-hammering policy are
application-owned. No general-purpose disk or Moka response cache is needed.
+137
View File
@@ -0,0 +1,137 @@
# Wakey Roadmap
Last updated: 2026-10-12. This records agreed work and follow-ups, not a release
promise. Checked items are implemented; live validation is called out separately.
## Completed Observability
- [x] Shared optional OTLP setup for traces, logs, and metrics in wakey-core.
- [x] Basic/Bearer authorization supplied through a named environment variable.
- [x] OpenWrt UCI configuration and systemd environment-file support, with setup guides.
- [x] Cross-process command trace context; verified live on a CC-to-agent wake.
- [x] Inventory source, merge, device-storage, and fleet-operation spans.
- [x] Agent connection phase spans and retry events, without entered guards across awaits.
- [x] Terminal snapshot generation, transport attachment, resume, and backpressure instrumentation.
- [x] Separate hostname-resolution and neighbor-table spans; a live slow wake spent about four seconds in resolution.
- [x] Metrics recipes for rates, duration averages/percentiles, terminal activity, and snapshots.
- [x] Authenticated live logs, metrics, and traces confirmed through Grafana's read-only API.
See [telemetry setup](telemetry.md), [metrics recipes](telemetry-recipes.md), and
[OpenWrt UCI](openwrt-uci.md). Terminal instrumentation has automated coverage;
live browser recovery and shutdown behavior are not established by those checks.
## Device Management And Presentation
- [x] Endpoint-derived presence on snapshot writes and fleet reads; endpoint-less legacy rows retain their summary. CLI ordering matches the core signal order.
- [x] Make **forget remembered device** reachable in the frontend, with confirmation. The existing backend removes the known identity and its identifiers, not agent observations. An observed device may reappear as unknown.
- [x] Add remembered-device rename support, with backend validation and frontend editing (`PATCH /api/v1/control/devices/{device_id}`). Pinned state and identifiers are preserved.
- [ ] Check and complete editing of remembered-device notes.
- [x] Replace generic unnamed-row labels with useful fallbacks. Prefer saved name, hostname, then `Device: <mac>`, then `Device: <ip>`; retain a generic label only when neither address exists. Presence stays in the badge, not the name. Inactive IPs can label IP-only rows without becoming active IPs or wake routes. Unknown-only fleet groups remain unknown.
- [ ] Review frontend visibility defaults. Keep an explicit all-rows option; do not hide evidence just to fix poor labels. The user deliberately enabled all-row querying.
- [x] Keep device details current after identity mutations change the grouping key or list filters exclude the result. Exact fleet details and full saved-identity reads follow the mutation's explicit ID; no shared-IP matching or stale-control fallback. Remember/Attach/Rename verified with mocked browser flows on desktop, Remember/Rename on mobile; backend tests cover filtering, old-key rejection and lookup beyond the list cap. Forget deliberately closes; detaching stays on the saved identity instead of guessing among split observations.
Identifier detachment already exists in the current frontend source; it is **not**
the requested whole-device removal. No automatic identity promotion or deletion
of remembered identifiers based on observation expiry.
## Telemetry Follow-Ups
- [x] Human-readable agent/CC config durations with unit-aware legacy loading, stderr deprecation warnings, and canonical init-config output. See [configuration durations](config-durations.md).
- [x] CC device retention by last snapshot inclusion (`device_retention = "60d"`, zero disables), independent of audit history and preserving saved identities.
- [x] Lazy grouped fleet-view cache with store/connection invalidation and stale-build rejection. See [fleet cache](fleet-cache.md).
- [x] Separate console, OTLP log, and trace filters using per-layer filtering. Explicit signal config overrides `RUST_LOG`, then CLI verbosity supplies defaults. Unconfigured defaults remain info-level; exporter-failure logs stay local. Live validation pending.
- [x] Upgrade the matched OpenTelemetry stack to 0.33 with exporter-managed backoff/jitter retries. Controlled collector tests cover all-signal recovery, bounded retries, and no retry on authentication rejection; live outage validation remains pending.
- [ ] Record hostname-resolution success/failure without exporting hostnames or resolved addresses. Current spans show timing but do not explicitly classify the result.
- [ ] Investigate the slow resolver with a reproducible device-side check. Timing isolated the phase, not the cause; do not treat instrumentation as a fix.
- [x] Propagate optional W3C trace context for periodic/requested WS snapshots so agent collection and CC persistence can be inspected together. Wire compatibility and context linkage tested; live Grafana inspection confirmed CC storage is a child of agent collection in the same trace. Storage can start after collection ends: this is an asynchronous handoff, not a persistence acknowledgement.
- [x] Add current-state gauges: retained device/endpoint rows per agent and unfiltered grouped fleet identities split saved/unsaved. Sample independently every 30 seconds with bounded revision checks; replace labels and suppress failed samples. Collector and state lifecycle tests included; dashboard recipes ready.
- [ ] Decide whether snapshots need persistence acknowledgements. The existing sent-device counter does not prove CC storage; any confirmed-storage metric needs an authoritative measurement point.
- [x] Break down snapshot persistence timing into pool acquisition, transaction acquisition, row replacement, and commit child spans. Shared write acquisition retains SQLx ownership and `BEGIN IMMEDIATE`; snapshot row work stays in the caller's transaction. Existing rollback and cache-refresh tests cover behavior. Live trace screenshot confirmed all phases: about 83 microseconds acquiring a connection, 154 microseconds beginning the transaction, 12.8 ms replacing rows, and 18.94 ms committing. This sample does not justify changing SQLite durability or prove a persistent bottleneck. See [telemetry span semantics](telemetry.md#signals).
The existing snapshot counter is cumulative collection volume, not unique devices
or current fleet size. Metric labels should remain bounded; no per-device labels.
## Process And Host Visibility
- [x] Add Linux process age/RSS and host uptime gauges for agent and CC through opt-in OTLP, using the existing collection interval. Core owns OS-independent instruments; wakey-linux supplies the optional procfs reader. Missing data omits observations; no added labels, config fields, health routes or polling tasks. Collector coverage verifies units and values; router/live dashboard validation pending.
- [x] Add cumulative process CPU time (counter) and current open-FD count (gauge) through the same Linux reader and OS-independent instruments. Exclude child processes, omit failed samples, and document one-core CPU-rate interpretation and sampling FD overhead. Extend collector/reader coverage rather than adding timing-based tests; live validation pending.
- [ ] Add start-time/version metadata if needed. Keep version as resource metadata rather than repeating it on every sample.
- [x] Add total/available host memory and 1/5/15-minute load gauges through the optional Linux reader, with byte conversion owned by procfs and fixed load-period labels. Omit unavailable MemAvailable instead of substituting free memory; document kernel views versus container limits. Collector/reader coverage included; live validation pending.
- [ ] Complete a small host summary with hostname, OS/kernel and CPU count. Sources must tolerate missing Linux files; not every agent host is a router.
- [ ] Display CC and agent process/host information in Fleet Health and agent details: version/name, process/host uptime, RSS, CPU time/usage, open FDs, available/total host memory and load where supported. OTLP export is not the UI's data source; the UI must work without a collector.
- [ ] Add typed agent status snapshots over the existing authenticated WebSocket, on a modest timer and when requested. Reuse Linux collection rather than introducing separate parsers; CC retains each agent's latest sample with received time and connection status. Show stale/disconnected or unavailable values explicitly, never as zero/current. Keep routine samples in memory initially, not an unbounded DB history.
- [ ] Expose the CC's own sampled status and retained agent summaries through protected control APIs. Keep `/healthz` unchanged and do not expose environment variables, credentials or command lines. CPU percentages require successive cumulative CPU/time samples; do not label raw CPU seconds as utilization. No expensive host reads on every UI request.
- [ ] Keep `/healthz` as cheap liveness; consider a separate bounded `/readyz` database-access check for CC. Collector outages and disconnected fleet agents must not make a functioning CC unready.
- [ ] Add application resource gauges where useful: DB pool usage, connected agents, pending commands, and active terminal sessions. Check existing instruments first to avoid duplicates; distinguish pool pressure from host/process pressure.
## Device Diagnostics
- [ ] Add agent-side ICMP ping through the existing command relay, with an explicit IP and selected agent/network route. Bound probe count, total duration, output and concurrent work; no shell interpolation. Account for missing tools and ICMP permissions, and support IPv4/IPv6 where available.
- [ ] Return probe replies, loss and round-trip times; offer Ping alongside Wake in device details. MAC-only devices cannot be pinged without an IP. A reply means that IP responded from that agent's network, not proof of saved identity; no reply must not automatically mark a device offline or remove an identifier.
## Optional Agent Sources And Capabilities
These are exploration items, not a commitment to a router-only model or a new
message bus. Sparse WSL inventory is legitimate; missing evidence is not failure.
- [ ] Discover and advertise usable observation sources separately from supported commands and configured permissions. Extend the existing hello/capability mechanism where appropriate; CC/UI must tolerate missing sources and older agents. Do not infer router status from Linux alone.
- [ ] Investigate read-only Wi-Fi station data on the actual router: signal in **dBm**, association/interface, rates and traffic counters where available. Evaluate driver-supported `iw`/netlink or local `ubus`/hostapd interfaces before choosing a dependency. Keep measurements scoped to agent/interface/station with source and capture time; they are not permanent identity or globally valid presence. UI may show a signal badge only when supported and sufficiently fresh.
- [ ] Investigate interface lifecycle hooks for WAN/link changes, keeping scripts minimal and logic in the binary. Interface up/down does not prove Internet reachability; any active connectivity probe needs an explicit target and bounded policy. Existing DHCP/neighbor hooks remain independent evidence, not a way to enrich or overwrite other sources.
- [ ] Keep source support, operator authorization and local agent policy distinct. Capability advertisement is not permission: CC checks authorization and the agent enforces configured limits. New diagnostic APIs should be typed, protected operations, not arbitrary shell, UCI or bus calls exposed to the browser.
OpenWrt [hotplug](https://openwrt.org/docs/guide-user/base-system/hotplug) provides
event hooks; [ubus](https://openwrt.org/docs/techref/ubus) is local IPC/RPC, and
[UCI](https://openwrt.org/docs/guide-developer/ubus/uci) manages configuration.
None is a Kafka-style retained observation history. Verify what the vendor
firmware actually exposes before making any of them an agent requirement.
## Origin Authentication
- [x] Replace the nonempty assertion matcher in the Caddy template with `forward_auth`. The initial `lb.ldlda.com` probe reached Cloudflare; the later `mails.ldlda.com` probe reached an origin and confirmed 403 without an assertion versus 200 with a forged assertion on the same IP. This is a reproduced bypass, not just a theoretical concern; production rollout remains required.
- [x] Add CC's `/internal/auth/verify` endpoint with configured issuer/audience/key URL, RS256 signature and required claim validation, bounded cached key retrieval, single-flight refresh and outage cooldown. Return 204/401/503 without exposing tokens or identity data. Configured verification requires loopback binding, and `init-config --from-config` preserves it. See [origin authentication](origin-auth.md).
- [x] Cover forged/expired/wrong-audience/missing-claim tokens, key rotation/removal (including an empty set), duplicate assertions, unavailable/malformed/oversized key responses, cooldown and concurrent fetches. Router coverage verifies the oracle is separate from public/control handlers; actual Caddy enforcement is deployment-owned and still requires validation.
- [x] Use `http-cache-semantics` for issuer-supplied HTTP freshness instead of a hardcoded signing-key TTL. Preserve bounded streaming reads, force revalidation on unknown key IDs, and handle ETag/Last-Modified 304 responses without reparsing a body. Tests cover fresh reuse, Age, no-cache/no-store, unspecified freshness, conditional rotation and invalid 304 rejection; no sleeps required.
- [ ] Deploy the new CC verifier and Caddy policy for root/UI/control HTTP and operator WS handshakes. Keep public agent paths outside Access checks and the verifier unexposed publicly. Validate Caddy configuration, real Access login, agent connectivity, protected WebSocket rejection, and forged-header direct-origin rejection. Authentication failures must never fall back to header-only acceptance.
## Multi-CC Planning
- [ ] Consolidate stable CC/local-agent IDs, forwarded display names, per-CC enrollments, and agent config restructuring. See [multi-CC proposal](multi-cc-plan.md). Identity/name exchange and terminal ownership must be defined before adding connection workers; no CC-to-CC state synchronization is planned.
## Validation And Reliability
- [x] Bound fleet-cache rebuilds to three attempts under sustained mutations; return retryable HTTP 503 `fleet_busy` rather than silently serving stale wake routes. Deterministic limit/recovery tests included.
- [x] Separate fleet wake selection from dispatch; wake lookup uses the complete cached view rather than the presentation list's 1,000-row cap. Automated coverage checks explicit-route rejection and lookup beyond the cap; live checks confirm missing-device and invalid-route errors without dispatching wakes.
- [x] Share device read assembly within a single SQLite read transaction. Query-plan inspection on the test database with Python SQLite confirmed all six per-agent reads use primary-key searches; full-fleet reads scan intentionally, with covering indexes for MAC/IP projections and no temporary sort. No additional indexes justified by this check.
- [x] Separate fleet refresh selection, relay, decoding/storage, and aggregation. Preserve concurrency of eight and per-agent failures; tests cover disconnected agents, sorted partial results, invalid payload preservation, and valid empty snapshot replacement.
- [x] Add a refresh integration regression: a simulated agent answers through the production command relay; its inventory reaches SQLite, invalidates a previously populated fleet cache, and appears in the next fleet read. A disconnected agent does not cancel success; duplicate selection sends only one command. This covers the CC application path, not a real agent process or WebSocket transport.
- [ ] Reproduce/check Ctrl-C cleanup on the test device: process groups, PTYs, relay tasks, and telemetry shutdown. Leftovers were suspected, not confirmed.
- [ ] Exercise collector unavailability and recovery with running agent/CC instances. Verify normal operations continue and telemetry queues remain bounded; outage losses are expected under the current best-effort policy.
- [ ] Validate terminal recovery instrumentation live: generation timing/size, transport attach/resume, and backpressure episodes ending in drain or disconnect.
- [ ] Validate the revised UCI credential prompt and service environment on the live router.
## Watch, Not Yet Fix
- Fleet listing time is mostly device-store reads in observed traces. Measure
sustained latency and row counts before changing queries or indexes.
- Snapshot write durations vary. Existing store spans include pool/lock waits,
transaction work, and result assembly where applicable; they are not pure SQL timings.
## Deferred
- Pinned-state editing: currently not needed for the small remembered fleet.
- Browser-render acknowledgement: attach acceptance and snapshot generation do
not prove xterm finished restoring. This would require additional protocol work.
- Retaining terminal images across recovery: text-screen snapshots do not provide image replay.
- CPU/heap profiling: use targeted profiling when a measured issue calls for it;
OTLP traces are not CPU profiles or flame graphs.
- Grafana dashboard construction is the user's exercise; keep improving the recipe book rather than taking over dashboard editing.
## Release Notes
- No version bump is made by this roadmap. Additive optional config fields alone
do not require 0.4.0; reconsider if compatibility or defaults change materially.
- Recheck live telemetry after deployment. A Grafana volume reset can remove
history and invalidate service-account tokens or data-source UIDs.
- Never commit Grafana tokens, UCI credentials, or router backups.
+294
View File
@@ -0,0 +1,294 @@
# Wakey Metrics Recipes
Use Grafana Explore with your Prometheus-compatible data source and the Code
query editor. These recipes assume standard OTLP-to-Prometheus name conversion.
Discover your actual series first:
```promql
count by (__name__, job) ({__name__=~"wakey[._].*"})
```
With Alloy's Prometheus exporter, service names normally become `job`, and agent
instance IDs become `instance`. Inspect the returned labels before adding filters.
For example, append `{job="wakey-agent"}` to a metric selector only if that is
the job value you actually see. Metrics export every 30 seconds; use a time range
that includes recent activity and allow at least two exports for rate queries.
## Metric Types
| Type | What it records | How to read it |
| --- | --- | --- |
| Counter | Cumulative events or bytes since process startup | `rate` for per-second throughput; `increase` for a window's estimated total |
| UpDownCounter | Adds and subtracts from a current quantity | Read the current value directly; do not use `rate` for active sessions |
| Gauge | Measures a current value, such as stored device rows | Read directly; do not use `rate` or `increase` |
| Histogram | Distribution of individual measurements | `_sum / _count` for an average; `_bucket` for estimated percentiles |
Counter resets on restart are handled by `rate` and `increase`. Apply those
functions **before** summing across instances so individual resets remain visible.
## Process And Host
Discover the new gauges first (these are Linux-only):
```promql
count by (__name__, job, instance) ({__name__=~"wakey_(process|host)_.*"})
```
Process age and host uptime, in seconds:
```promql
wakey_process_uptime_seconds
```
```promql
wakey_host_uptime_seconds
```
Set Grafana's unit to a duration. Compare the two: process age resetting while
host uptime continues suggests a daemon restart; both resetting suggests a host
restart or a changed namespace/view. Missing samples are not a zero uptime or
proof of a restart. These are gauges: do not use `rate` or `increase` on them.
Resident process memory, in bytes:
```promql
wakey_process_memory_resident_bytes
```
Set the unit to **bytes (IEC)**. Keep `job` and `instance` in the legend to compare
agent and CC separately. RSS includes shared/file-backed pages and is not heap
allocation alone. A missing series can mean disabled telemetry, an unsupported
platform, unavailable procfs, or export trouble. No new health endpoint or host
inventory is provided here; do not sum host uptime from multiple daemons.
CPU consumption as a percentage of **one CPU core**:
```promql
100 * rate(wakey_process_cpu_time_seconds_total[5m])
```
Set the unit to **percent (0-100)**. A multithreaded process can exceed 100%;
this is not normalized by the host's CPU count. The counter includes daemon
user/system CPU, not its child shells or commands. Allow at least two exports;
`rate` handles counter resets on process restart.
Current open descriptors:
```promql
wakey_process_open_fds
```
Read directly as a count, not a rate. The sampling read can contribute temporary
descriptors. Persistent growth can warrant investigation, but sockets, terminal
sessions and pool connections legitimately change the count too.
Host usable/available RAM, in bytes:
```promql
wakey_host_memory_total_bytes
```
```promql
wakey_host_memory_available_bytes
```
Set units to **bytes (IEC)**. Estimated percentage not available for new work:
```promql
100 * (1 - wakey_host_memory_available_bytes / wakey_host_memory_total_bytes)
```
Available includes reclaimable memory and is not merely free RAM. Missing
`MemAvailable` leaves a gap rather than substituting `MemFree`. Do not sum host
RAM from multiple daemon instances on the same host, or interpret these kernel
values as a container's cgroup limit.
Load averages by period:
```promql
wakey_host_load
```
Use `{{job}} / {{instance}} / {{period}}` as the legend. Fixed periods are `1m`,
`5m`, and `15m`. Read directly as a load count, not a percentage or a rate:
Linux includes runnable and uninterruptible tasks; a high load can include I/O
waiting rather than CPU work. These values are not normalized by CPU count.
## Operations
Completed attempts per second, including errors and timeouts:
```promql
sum by (job, operation, outcome) (rate(wakey_operations_total[5m]))
```
Estimated attempts over the last hour:
```promql
sum by (job, operation, outcome) (increase(wakey_operations_total[1h]))
```
Average duration over the last five minutes:
```promql
sum by (job, operation) (rate(wakey_operation_duration_seconds_sum[5m]))
/
sum by (job, operation) (rate(wakey_operation_duration_seconds_count[5m]))
```
Set Grafana's unit to **seconds**. This is a weighted average, not an average of
instance averages. Both successful and unsuccessful attempts are included;
add `outcome="ok"` to both selectors for successful attempts only.
Estimated p95 duration:
```promql
histogram_quantile(
0.95,
sum by (le, job, operation) (
rate(wakey_operation_duration_seconds_bucket[5m])
)
)
```
This needs classic histogram bucket series. Keep `le` in the grouping: it is
the bucket boundary, in seconds. p95 is an estimate from those boundaries,
not an exact sort of recorded durations. Few operations make percentiles noisy.
CC relay duration includes waiting for the agent; agent execution duration
measures its dispatch separately. Do not sum both and call that user latency.
## Terminals
Active PTY workers by agent, including detached sessions:
```promql
sum by (job, instance) (wakey_terminal_active)
```
Read this directly as a count. It is not a count of browser tabs or attachments.
PTY output bytes per second:
```promql
sum by (job, instance) (rate(wakey_terminal_output_bytes_total[5m]))
```
Input bytes per second:
```promql
sum by (job, instance) (rate(wakey_terminal_input_bytes_total[5m]))
```
Set the unit to **bytes/sec**. Output is measured at the PTY read, even while
detached; it is not WebSocket wire traffic or confirmed browser delivery.
Relay queue-full encounters over the last fifteen minutes:
```promql
sum by (job, instance) (increase(wakey_terminal_backpressure_total[15m]))
```
This counts encounters, not their duration and not dropped chunks. A burst of
image output can raise it while output still arrives intact through backpressure.
Average duration of completed backpressure episodes, in seconds:
```promql
sum by (job, instance, outcome) (
rate(wakey_operation_duration_seconds_sum{operation="terminal_backpressure_wait"}[5m])
)
/
sum by (job, instance, outcome) (
rate(wakey_operation_duration_seconds_count{operation="terminal_backpressure_wait"}[5m])
)
```
An episode starts when the output channel is full and ends when the pending
backlog drains or the relay disconnects. It is not per-frame network latency;
unfinished episodes do not appear until they end. Keep the outcome grouping so
disconnected episodes are not confused with successfully drained ones.
## Snapshots
Device entries in successfully sent snapshots over the last hour:
```promql
sum by (job, instance) (increase(wakey_snapshot_devices_total[1h]))
```
Repeated snapshots count the same devices again. This is collection volume,
**not unique devices, current fleet size, or confirmed CC persistence**.
## Current Devices And Endpoints
These gauges are emitted by CC. Counts are sampled at startup and every 30 seconds,
independently of UI requests, and exported on the normal metrics schedule. Allow
up to two intervals for a change to appear. The snapshot counter above cannot
substitute for these gauges.
A **device** is a grouped device identity. An **endpoint** is one observed address
entry with an IP, optional MAC/interface, source, and presence. One PC can have
multiple IPv4/IPv6 endpoints, and different sources or agents can observe the
same address. An endpoint here is not an HTTP API route.
| Panel | Scope | Suggested visualization |
| --- | --- | --- |
| Stored devices by agent | Device rows currently retained in CC for each agent; not globally unique identities | Bar gauge, one value per agent |
| Stored endpoints by agent | Endpoint rows currently retained in CC for each agent, including inactive entries; not unique IPs | Bar gauge, one value per agent |
| Fleet devices | Grouped fleet identities, split into saved and unsaved | Stat, one value per category |
Stored device rows by agent:
```promql
sum by (job, agent_id) (wakey_stored_devices{job="wakey-control-plane"})
```
Stored endpoint rows by agent:
```promql
sum by (job, agent_id) (wakey_stored_endpoints{job="wakey-control-plane"})
```
Grouped fleet devices by manual identity status:
```promql
sum by (job, identity) (wakey_fleet_devices{job="wakey-control-plane"})
```
Adjust the `job` selector to your actual service label. These queries assume one
CC owns the fleet; do not sum replicas of the same database as distinct devices.
Enrolled agents with no stored rows report zero. After revocation, an agent can
remain represented while its device rows are retained. When neither enrollment
nor stored rows exist, the sampler stops reporting that agent label.
Use Grafana's **short** unit with zero decimal places. Read the gauges directly;
do not apply `rate` or `increase`. Counts must reflect unfiltered CC state, not
the last UI search or visibility filter. An agent going offline does not by
itself delete its stored rows, so these counts are not online-device counts.
Do not sum per-agent device counts and label that value "unique fleet devices":
the same device can be observed by more than one agent. Likewise, an endpoint
count is not a count of distinct IP addresses. Saved/unsaved describes manual
identity management, not online/offline/unknown presence.
Failed refreshes suppress observations until sampling recovers; they do not report
zero or keep exporting an old sample. Prometheus may still show its last value
until that series becomes stale. Export callbacks only read the in-memory sample;
they never wait on database work. Sampling is disabled when OTLP is disabled.
## Empty or Strange Results
- No series: generate the relevant activity, wait for export, and check the metrics pipeline.
- Different names: use the discovery query; collector translation can change suffixes and labels.
- `NaN` average: no operations occurred in the window, so the denominator is zero. Show a gap, not a fake zero latency.
- Empty `rate`: it needs multiple samples. Try a longer window and check the time range.
- Fractional `increase`: Prometheus extrapolates to the window boundaries; event counts can therefore appear fractional.
- Stale active count: the last exported value is not an immediate liveness check after a crash or network loss.
- No `instance` label: CC does not currently set a service instance ID; agent telemetry does.
## References
- [Wakey telemetry setup and limitations](telemetry.md)
- [Prometheus rate, increase, and histogram_quantile](https://prometheus.io/docs/prometheus/latest/querying/functions/)
- [Alloy OTLP-to-Prometheus conversion](https://grafana.com/docs/alloy/latest/reference/components/otelcol/otelcol.exporter.prometheus/)
+251
View File
@@ -0,0 +1,251 @@
# Telemetry
CC and the agent daemon share the optional `wakey-core/telemetry` module.
Local logs remain enabled. Configure an OTLP **gRPC** receiver to additionally
export traces, structured logs, and metrics; HTTP/4318 is not supported in this slice.
CC configuration:
```toml
[telemetry]
otlp_endpoint = "http://127.0.0.1:4317"
authorization_env = "WAKEY_OTLP_AUTHORIZATION"
service_name = "wakey-control-plane"
json_logs = true
```
Agent configuration (replace the example with the collector's WireGuard address):
```toml
[telemetry]
otlp_endpoint = "http://10.5.0.1:4317"
authorization_env = "WAKEY_OTLP_AUTHORIZATION"
service_name = "wakey-agent"
json_logs = false
```
Omit `otlp_endpoint` to disable exporting. Omit `authorization_env` for a receiver
that requires no authentication. Existing configs need no changes.
An empty agent service name uses `wakey-agent`; its enrolled agent ID becomes
the resource's `service.instance.id`, not a metric label. Telemetry config changes
require a daemon restart, not SIGHUP. Short-lived enroll/reload/observe commands
only log locally and do not initialize exporters.
## Receiver and filtering
The collector must enable OTLP receivers in **traces, logs, and metrics** pipelines.
Loopback is sufficient for CC on the same host/network namespace. The router
needs a collector listener reachable over WireGuard; do not expose an unauthenticated
receiver on the public Internet. This initial setup assumes plaintext inside that
tunnel. `json_logs` changes local output,
not whether OTLP logs are exported.
## Credentials and services
The OpenWrt agent uses `/etc/config/wakey`; see the
[UCI setup guide](openwrt-uci.md) for commands and permissions.
The CC uses a systemd environment file as described below.
`authorization_env` names an environment variable containing the complete header:
`Basic <base64(username:password)>` or `Bearer <token>`. With exporting enabled,
missing/empty/invalid values fail startup; credentials are never written to TOML
or included in error messages. Metadata is marked sensitive for Debug output.
Base64 is not encryption: use the WireGuard/SSH tunnel or another protected transport.
The systemd CC reads the optional `/etc/wakey-control-plane/environment` file.
Use this portable literal format, **without quotes or `export`**:
```text
# Replace this placeholder with the actual encoded credential locally.
WAKEY_OTLP_AUTHORIZATION=Basic BASE64_OF_USERNAME_COLON_PASSWORD
RUST_LOG=info
```
Protect the file with owner `root:root` and mode `0600`. systemd's manager reads it
before switching to the service user. Use the simple format above, with LF endings
and no inline comments or multiline values.
An absent file is allowed; configuring auth without providing its variable is not.
After changing the file, **restart** the service. On systemd, run `daemon-reload`
once after installing the updated unit. OpenWrt's HUP reload does not reload the
process environment. For a foreground WSL test, export the variable in that shell
and use `http://127.0.0.1:4317` with the SSH tunnel; do not put credentials in CLI args.
Console logs, OTLP logs, and traces can have independent filters:
```toml
[telemetry]
console_filter = "info"
otlp_log_filter = "debug"
trace_filter = "info"
```
For each signal, an explicit filter wins over `RUST_LOG`, which wins over CLI
verbosity (`-v`). With no filters, environment override, or verbosity flags, the
application defaults remain info-level with SDK warnings. Metrics are unaffected.
Explicit filters must be valid and nonempty; changing them requires a restart.
Without explicit filters, `RUST_LOG=warn` suppresses informational spans and logs.
Use `wakey_agent=info,wakey=info,wakey_core=info,opentelemetry=warn` for the agent and
`wakey_control_plane=info,wakey_core=info,opentelemetry=warn` for CC. Exporter warnings
remain local to prevent export-failure feedback loops. Both OTLP logs and traces
exclude OpenTelemetry SDK targets and the `h2`, `hyper`, `hyper_util`, `tonic`
and `tower` crate targets, even under broad debug filters. These transport
crates also serve application traffic: their diagnostics stay console-only,
while Wakey's command/storage/relay spans still export. Console filters remain
independent. Increasing verbosity exports application debug events too; inspect
them before enabling it broadly.
## Signals
- `relay_command` on CC propagates W3C context in an optional command field.
`execute_command` on the agent adopts it; older messages/agents remain compatible.
- `collect_device_snapshot` and `store_device_snapshot` measure collection and
persistence as linked spans across the agent WebSocket. The snapshot carries
optional W3C context from collection; CC adopts it after authentication checks.
Periodic and requested syncs use the same path. Old messages and empty/invalid
context remain valid but do not create a cross-process link. Both processes
need tracing enabled and suitable filters/sampling to see both sides.
- Terminal create/attach/close/resume spans describe lifecycle operations, not
output chunks. Trace-linked OTLP logs use the SDK's tracing-context bridge.
- Inventory source spans separate neighbor, DHCP lease, and hook-store reads
from merging. `db_*` spans cover snapshot replacement, fleet reads, and manual
identity changes, including transaction waits and result assembly where applicable.
Snapshot replacement retains `db_replace_agent_snapshot` as its total duration,
with four sequential child spans:
- `db_pool_acquire`: obtaining a pooled connection, including any connection
setup/checks; it is not exclusively queue wait.
- `db_write_transaction_begin`: executing `BEGIN IMMEDIATE`, including SQLite
writer-lock wait and worker scheduling, not a direct lock-wait measurement.
- `db_snapshot_write_rows`: existing-key lookup, normalization, parent/child
writes, and deletion of devices missing from the complete snapshot.
- `db_snapshot_commit`: transaction commit, including its SQLite/worker work;
this does not isolate filesystem flush time.
Pool and transaction-begin spans come from the shared write helper, so they
also appear under other write operations. No per-row spans or SQL values are
recorded. A failed write rolls back through SQLx and has no commit span;
fleet cache invalidation still happens only after a successful commit.
- Fleet spans cover list/load/grouping, refresh fan-out with per-agent outcomes,
and wake dispatch. Counts distinguish grouped, filtered, and returned rows;
wake events identify the chosen agent and whether the route was explicit,
without recording device identifiers or addresses.
- Connectivity uses short `agent_dns`, `agent_connect`, `agent_handshake_send`,
and CC `agent_auth_verify` spans, rather than connection-long spans. Connect
attempts also contribute to operation metrics. Lifecycle events report retries
with backoff and CC disconnect duration. Sending credentials is not an auth ACK;
CC's authentication event is the authoritative result. DNS diagnostics are a
separate lookup, not a measurement of the resolver inside WebSocket connect.
- Terminal recovery uses `terminal_snapshot_generate` (encoded byte count),
transport-attachment spans, and `terminal_snapshot_request`. These measure
local work, not browser restoration or end-to-end image replay. Resume operation
success means credentials were queued for the worker. `terminal_backpressure_wait`
operation durations cover one full-queue backlog episode until it drains (`ok`)
or disconnects (`disconnected`); cancellation can retain the default `error` outcome.
Instrument operation boundaries rather than individual rows or terminal chunks.
Use `skip_all`, explicitly allow count fields, and instrument async futures rather
than holding entered span guards across awaits. Do not record query arguments,
SQL parameters, device payloads, or credentials. Span names are fixed across requests.
Metrics are exported every 30 seconds and at orderly shutdown:
The table uses OpenTelemetry instrument names. Prometheus conversion typically
replaces dots with underscores and adds type/unit suffixes; histograms produce
multiple series. See the [metrics recipe book](telemetry-recipes.md) for discovery
queries, rates, averages, percentiles, and Grafana units.
| Metric | Meaning |
| --- | --- |
| `wakey.operations` | Completed command/snapshot attempts, labeled by operation and outcome |
| `wakey.operation.duration` | Corresponding duration histogram in seconds |
| `wakey.snapshot.devices` | Cumulative devices in snapshots successfully sent by the agent |
| `wakey.stored.devices` | CC gauge of retained device rows, labeled by `agent_id` |
| `wakey.stored.endpoints` | CC gauge of retained endpoint rows, including inactive entries, labeled by `agent_id` |
| `wakey.fleet.devices` | CC gauge of unfiltered grouped identities, labeled by `identity` (`saved` or `unsaved`) |
| `wakey.process.uptime` | Linux gauge: seconds since this process's kernel-reported start, including suspend |
| `wakey.process.memory.resident` | Linux gauge: approximate resident memory in bytes, from VmRSS |
| `wakey.process.cpu.time` | Linux counter: cumulative user + system CPU seconds for all process threads, excluding children |
| `wakey.process.open_fds` | Linux gauge: current count of open process file descriptors |
| `wakey.host.uptime` | Linux gauge: uptime in seconds reported by the process's procfs view, including suspend |
| `wakey.host.memory.total` | Linux gauge: total usable RAM in bytes from the visible meminfo |
| `wakey.host.memory.available` | Linux gauge: estimated available RAM in bytes; omitted if MemAvailable is unavailable |
| `wakey.host.load` | Linux gauge: load average, with fixed `period` labels `1m`, `5m`, `15m` |
| `wakey.terminal.active` | Agent PTY workers currently alive |
| `wakey.terminal.input.bytes` | Input bytes received by the terminal relay |
| `wakey.terminal.output.bytes` | Output bytes read from the PTY, including while detached |
| `wakey.terminal.backpressure` | Relay queue-full encounters, not dropped output |
Metric labels do not include request/session IDs, MACs, or IPs. New spans use
`skip_all` and explicitly select safe fields; terminal bytes and credentials are
not attached. Profiles, host CPU-utilization metrics, connected-agent gauges, and export-loss
dashboards are not part of this initial slice.
Process and host gauges are registered automatically for Linux agent/CC daemons
when OTLP is enabled. `wakey-core` owns the OS-independent instruments and
`ProcessMetricsSource` interface; `wakey-linux` supplies the procfs reader via
its optional `telemetry` feature. Each daemon attaches that reader to its
telemetry guard, so core has no Linux dependency or filesystem reads.
Their small procfs reads run during the existing 30-second
metric collection and final shutdown collection; no independent poller or task
is started. Non-Linux builds omit these gauges. Missing/unreadable procfs data
omits the affected observation instead of reporting zero or failing the daemon.
No hostname, PID, command line or environment values are exported by this slice.
Service/instance resource attributes identify each daemon; two daemons on the
same host can report the same host uptime, so do not sum it across processes.
CPU time is not elapsed time or CPU percentage: use its rate for consumption.
Open-FD sampling can temporarily open descriptors counted by the measurement.
Process metrics describe the daemon itself, not its child shells/PTY programs
or the entire host. CPU/FD collection is also supplied by `wakey-linux`;
unsupported platform readers may omit these optional measurements.
Host memory/load come from the same optional Linux reader. `MemAvailable`
estimates memory reusable without swapping and is not `MemFree`; no fallback
is invented on older kernels. Load averages include runnable and uninterruptible
tasks, so they are not CPU percentages. These are the visible kernel/procfs
figures, not cgroup memory limits or container-specific load measurements;
multiple daemons may export duplicate views of the same host.
RSS includes anonymous, file-backed and shared resident pages, not just heap,
and is an approximate kernel measurement. Process age uses procfs start ticks
and uptime, not wall-clock subtraction or telemetry initialization time.
Container/time namespaces can change the visible host clock; this is the
process's Linux view, not an assertion about a physical machine's boot time.
The Linux parser is [procfs](https://docs.rs/procfs/0.18.0/procfs/), with optional
default features disabled. Public `/healthz` remains unchanged.
Current-state fleet gauges sample independently every 30 seconds, with bounded
revision retries to avoid mixed-state counts. Enrolled empty agents report zero;
removed labels disappear when no enrollment or retained rows remain. Failed samples
are omitted, not converted to zeros. No per-device labels are emitted. See the
recipe book for scopes, queries, and the distinction between devices and endpoints.
## Failure policy
Trace and log queues are capped at 256 records each, with export batches of 64
and a 3-second request timeout. Export happens off the application path. The
OTLP exporters use their recommended retry policy: up to three retries after
the first attempt, exponential backoff and jitter, within the exporter timeout
budget. Temporary transport/receiver failures can recover; authentication
rejection and partial-success responses are not retried. Requests already in
flight can exceed the retry budget, so it is not a hard wall-clock deadline.
The application does not wrap exports in another retry loop. On an
outage, telemetry can be dropped rather than accumulating unbounded router RAM;
terminal output follows its existing lossless backpressure policy independently.
Automated receiver tests reject the first export of each signal and confirm
recovery, check the retry-attempt limit on a persistent outage, and confirm that
bad credentials cause only one attempt. These tests do not establish durable
delivery during a long outage; bounded queues can still drop telemetry.
The bound is a record count, not an absolute byte limit on arbitrary log messages.
Providers flush on orderly daemon exit (Ctrl-C/SIGTERM), on a blocking worker while
Tokio remains alive. Only completed spans are exported; this is not graceful draining
of every in-flight request. SIGKILL/power loss cannot flush. This is not a persistent
telemetry spool.
## Validation
```sh
cargo test -p wakey-core --features telemetry --test telemetry
```
The test starts a temporary gRPC collector and verifies all three signals,
command parent/child IDs, log correlation, and shutdown delivery without sleeps.
+5
View File
@@ -0,0 +1,5 @@
server_url = "https://control-plane.example.com"
agent_id = "REPLACE_ME_AGENT_ID"
agent_token = "REPLACE_ME_AGENT_TOKEN"
reconnect_base_ms = 1000
reconnect_max_ms = 30000
+11
View File
@@ -0,0 +1,11 @@
data_dir = "/var/lib/wakey-control-plane"
bind = "0.0.0.0:8080"
public_url = "http://127.0.0.1:8080"
state_file = "state.db"
command_timeout_ms = 30000
enroll_token_ttl_seconds = 86400
pid_file = "wakey-control-plane.pid"
[telemetry]
service_name = "wakey-control-plane"
json_logs = false
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "lda-ipjs"
description = "ip -j show schemas"
version = "0.0.4"
edition = "2024"
publish = ["gitea"]
[features]
default = []
experimental-nl = ["dep:rtnetlink"]
[dependencies]
macaddr = { version = "1", features = ["serde", "serde_std"] }
strum = { version = "0", features = ["derive", "strum_macros"] }
serde_json = "1"
serde = { version = "1", features = ["derive"] }
serde_with = { version = "3", features = ["json"] }
thiserror = "2"
anyhow = "1"
tokio = { version = "1", features = [
"fs",
"process",
"rt-multi-thread",
"io-util",
"macros",
] }
futures = "0"
[target.'cfg(unix)'.dependencies]
rtnetlink = { version = "0", optional = true }
Loaded 100 of 409 files, more files were not shown because too many files have changed in this diff. Show more