Compare commits

..

9 Commits

Author SHA1 Message Date
25c0451489 feat: cfg skill with topic-based docs (general/contract/onboarding/admin)
cfg skill              — general usage (default), lists other topics
cfg skill contract     — API endpoints, KV layout, auth flow
cfg skill onboarding   — step-by-step new agent setup
cfg skill admin        — admin operations & user management
2026-05-09 03:55:06 +00:00
f48f951c50 feat: add cfg skill subcommand — built-in usage guide
cfg skill outputs comprehensive documentation including architecture,
all commands, API endpoints, and tips. Keeps docs in sync with code.
2026-05-09 03:38:59 +00:00
46f3eb11a3 chore: bump cfg to 1.1.0 2026-05-09 03:26:46 +00:00
0ec917bedd feat: add public profile support
- New KV prefix public:{agent_id}:{key} for public profile data
- Any authenticated user can read all profiles, write only to own
- Worker routes: GET /profiles, GET/PUT/DELETE /profile/:agent_id/:key
- CLI commands: cfg profile, cfg profile <id>, cfg profile set/unset, cfg profiles
2026-05-09 03:19:13 +00:00
a3b3c598ab feat: admin agent switcher - view any agent's config from WebUI
- Add agent selector dropdown in header (admin only)
- Return role in GET /config response
- Collect agents from both auth: and agent_tokens: KV prefixes
- Show 'viewing <agent>' badge when viewing another agent
- Non-admin users see only their own config (unchanged)
2026-04-22 16:13:51 +00:00
eadaa97caa fix: only mask secret values, show non-secret values in plaintext 2026-04-21 04:06:38 +00:00
58494b8fca feat: React webui with flags support, build-ui pipeline
- packages/webui: Vite + React + Tailwind v4, single-file bundle
- Dark industrial theme, Space Grotesk + JetBrains Mono
- Config table with scope/flag badges, masked values, search/filter
- Admin panel for agent management
- scripts/build-ui.sh generates worker/src/ui.ts from webui build
- Worker serves UI at GET / before auth check
2026-04-21 04:01:35 +00:00
117e334a07 refactor: bun monorepo, @shazhou/cfg CLI (TS), cleanup old cli/scripts
- Restructured as bun monorepo with packages/cfg and packages/worker
- CLI rewritten in TypeScript with modular architecture
- Published as @shazhou/cfg@1.0.0 (replaces @shazhou/config)
- Deprecated @shazhou/config on npm
- Removed legacy Python scripts and old cli-npm package
2026-04-21 02:59:24 +00:00
211533346b Merge pull request 'feat: env/secret flags for config entries' (#2) from feat/entry-flags into main 2026-04-21 02:41:58 +00:00
35 changed files with 2064 additions and 521 deletions

5
.gitignore vendored
View File

@ -1 +1,6 @@
node_modules/
dist/
.wrangler/
.npmrc
bun.lock
package-lock.json

View File

@ -1,474 +0,0 @@
#!/usr/bin/env node
// src/cli.ts
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
import { homedir } from "os";
var CONFIG_DIR = join(homedir(), ".config", "cfg");
var CONFIG_FILE = join(CONFIG_DIR, "config.json");
var CACHE_FILE = join(CONFIG_DIR, "cache.json");
var DEFAULT_ENDPOINT = "https://config.shazhou.work";
var ONE_DAY = 24 * 60 * 60 * 1000;
var TWO_HOURS = 2 * 60 * 60 * 1000;
function loadConfig() {
try {
return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
} catch {
return {};
}
}
function saveConfig(cfg) {
mkdirSync(CONFIG_DIR, { recursive: true });
writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + `
`);
}
function loadCache() {
try {
return JSON.parse(readFileSync(CACHE_FILE, "utf-8"));
} catch {
return null;
}
}
function saveCache(cache) {
mkdirSync(CONFIG_DIR, { recursive: true });
writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2) + `
`);
}
function getToken() {
const cfg = loadConfig();
const token = process.env.CFG_TOKEN || cfg.token;
if (!token) {
console.error("No token configured. Run: cfg token <TOKEN>");
process.exit(1);
}
return token;
}
function getEndpoint() {
const cfg = loadConfig();
return cfg.endpoint || process.env.CFG_ENDPOINT || DEFAULT_ENDPOINT;
}
async function api(method, path, body) {
const url = `${getEndpoint()}${path}`;
const headers = {
Authorization: `Bearer ${getToken()}`,
"Content-Type": "application/json"
};
let res;
try {
res = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined
});
} catch (err) {
console.error(`Error: ${err?.cause?.message || err?.message || "network error"}`);
process.exit(1);
}
if (res.status === 204)
return { data: null, status: 204 };
const text = await res.text();
let data;
try {
data = JSON.parse(text);
} catch {
data = text;
}
if (!res.ok) {
const msg = data?.error || text;
console.error(`Error: ${msg}`);
process.exit(1);
}
return { data, status: res.status };
}
async function trySyncRemote() {
const url = `${getEndpoint()}/config`;
const headers = {
Authorization: `Bearer ${getToken()}`,
"Content-Type": "application/json"
};
try {
const res = await fetch(url, { method: "GET", headers });
if (!res.ok)
return false;
const data = await res.json();
if (!data?.secrets)
return false;
const now = new Date().toISOString();
const cache = {
agent_id: data.agent_id,
secrets: data.secrets,
synced_at: now,
attempted_at: now
};
saveCache(cache);
return true;
} catch {
const cache = loadCache();
if (cache) {
cache.attempted_at = new Date().toISOString();
saveCache(cache);
}
return false;
}
}
function shouldAutoSync(cache) {
if (!cache)
return true;
const now = Date.now();
const syncedAt = new Date(cache.synced_at).getTime();
const attemptedAt = new Date(cache.attempted_at || cache.synced_at).getTime();
if (syncedAt >= attemptedAt && now - syncedAt < ONE_DAY) {
return false;
}
if (now - attemptedAt < TWO_HOURS) {
return false;
}
return true;
}
async function cmdSync() {
const { data } = await api("GET", "/config");
if (!data?.secrets) {
console.error("No secrets found");
process.exit(1);
}
const now = new Date().toISOString();
const cache = {
agent_id: data.agent_id,
secrets: data.secrets,
synced_at: now,
attempted_at: now
};
saveCache(cache);
const count = Object.keys(cache.secrets).length;
console.log(`✓ Synced ${count} keys (agent: ${cache.agent_id})`);
}
async function cmdEnv() {
let cache = loadCache();
if (shouldAutoSync(cache)) {
const ok = await trySyncRemote();
if (ok) {
cache = loadCache();
} else if (!cache) {
console.error("No local cache and sync failed. Run: cfg sync");
process.exit(1);
}
}
for (const [key, entry] of Object.entries(cache.secrets).sort(([a], [b]) => a.localeCompare(b))) {
if (entry.env === false) continue;
const escaped = entry.value.replace(/'/g, "'\\''");
console.log(`export ${key}='${escaped}'`);
}
}
async function cmdGet(key, remote) {
if (remote) {
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
console.log(data.value);
return;
}
let cache = loadCache();
if (shouldAutoSync(cache)) {
const ok = await trySyncRemote();
if (ok)
cache = loadCache();
else if (!cache) {
console.error("No local cache and sync failed. Run: cfg sync");
process.exit(1);
}
}
if (!cache) {
console.error("No local cache. Run: cfg sync");
process.exit(1);
}
const entry = cache.secrets[key];
if (!entry) {
console.error(`Error: ${key} not found in cache. Try: cfg sync`);
process.exit(1);
}
console.log(entry.value);
}
async function cmdSet(args) {
const shared = args.includes("--shared");
const noEnv = args.includes("--no-env");
const isSecret = args.includes("--secret");
const filtered = args.filter((a) => !["--shared", "--no-env", "--secret"].includes(a));
if (filtered.length < 2) {
console.error("Usage: cfg set [--shared] [--no-env] [--secret] <KEY> <VALUE>");
process.exit(1);
}
const [key, ...rest] = filtered;
const value = rest.join(" ");
const scope = shared ? "shared" : "personal";
const body = { value, env: !noEnv, secret: isSecret };
await api("PUT", `/config/${encodeURIComponent(key)}?scope=${scope}`, body);
const flags = [];
if (noEnv) flags.push("no-env");
if (isSecret) flags.push("secret");
const flagStr = flags.length ? ` [${flags.join(", ")}]` : "";
console.log(`${key} (${scope})${flagStr}`);
const cache = loadCache();
if (cache) {
cache.secrets[key] = { value, scope, env: !noEnv, secret: isSecret, updated_at: new Date().toISOString() };
saveCache(cache);
}
}
async function cmdUnset(args) {
const shared = args.includes("--shared");
const filtered = args.filter((a) => a !== "--shared");
if (filtered.length < 1) {
console.error("Usage: cfg unset [--shared] <KEY>");
process.exit(1);
}
const key = filtered[0];
const scope = shared ? "shared" : "personal";
await api("DELETE", `/config/${encodeURIComponent(key)}?scope=${scope}`);
console.log(`✓ Deleted ${key} (${scope})`);
const cache = loadCache();
if (cache && cache.secrets[key]) {
delete cache.secrets[key];
saveCache(cache);
}
}
async function cmdList() {
let cache = loadCache();
if (shouldAutoSync(cache)) {
const ok = await trySyncRemote();
if (ok)
cache = loadCache();
else if (!cache) {
console.error("No local cache and sync failed. Run: cfg sync");
process.exit(1);
}
}
if (!cache) {
console.error("No local cache. Run: cfg sync");
process.exit(1);
}
if (!cache.secrets || Object.keys(cache.secrets).length === 0) {
console.log("No keys found");
return;
}
const keys = Object.keys(cache.secrets).sort();
const maxLen = Math.max(...keys.map((k) => k.length));
for (const key of keys) {
const entry = cache.secrets[key];
const scope = entry.scope === "personal" ? "\x1B[32mpersonal\x1B[0m" : "\x1B[34mshared\x1B[0m ";
const flags = [];
if (entry.env === false) flags.push("\x1B[33mno-env\x1B[0m");
if (entry.secret) flags.push("\x1B[31msecret\x1B[0m");
const flagStr = flags.length ? " " + flags.join(" ") : "";
console.log(` ${key.padEnd(maxLen + 2)}${scope}${flagStr}`);
}
console.log(`
Total: ${keys.length} keys (agent: ${cache.agent_id})`);
console.log(`Last sync: ${cache.synced_at}`);
}
function cmdToken(token) {
const cfg = loadConfig();
cfg.token = token;
saveConfig(cfg);
console.log("✓ Token saved");
}
async function cmdAdminAddUser(args) {
const role = args.includes("--admin") ? "admin" : "agent";
const filtered = args.filter((a) => a !== "--admin");
if (!filtered[0]) {
console.error("Usage: cfg admin add <AGENT_ID> [--admin]");
process.exit(1);
}
const { data } = await api("POST", "/admin/token", { agent_id: filtered[0], role });
console.log(`✓ Created ${data.role} token for ${data.agent_id}`);
console.log(` Token: ${data.token}`);
}
async function cmdAdminRemoveUser(args) {
if (!args[0]) {
console.error("Usage: cfg admin remove <AGENT_ID>");
process.exit(1);
}
const { data } = await api("DELETE", `/admin/token/${encodeURIComponent(args[0])}`);
console.log(`✓ Revoked ${data.tokens_revoked} token(s) for ${data.agent_id}`);
}
async function cmdAdminListAgents() {
const { data } = await api("GET", "/admin/agents");
if (!data.agents?.length) {
console.log("No agents found");
return;
}
console.log("Agents:");
for (const agent of data.agents) {
console.log(` ${agent}`);
}
}
async function cmdAdminRefreshToken(args) {
if (!args[0]) {
console.error("Usage: cfg admin refresh <AGENT_ID>");
process.exit(1);
}
const agentId = args[0];
await api("DELETE", `/admin/token/${encodeURIComponent(agentId)}`);
const { data } = await api("POST", "/admin/token", { agent_id: agentId });
console.log(`✓ Refreshed token for ${data.agent_id}`);
console.log(` Token: ${data.token}`);
}
async function cmdAdminInspect(args) {
if (!args[0]) {
console.error("Usage: cfg admin inspect <AGENT_ID>");
process.exit(1);
}
const { data } = await api("GET", `/admin/agent/${encodeURIComponent(args[0])}`);
if (!data.secrets || Object.keys(data.secrets).length === 0) {
console.log(`No keys for ${data.agent_id}`);
return;
}
const keys = Object.keys(data.secrets).sort();
const maxLen = Math.max(...keys.map((k) => k.length));
for (const key of keys) {
const entry = data.secrets[key];
const scope = entry.scope === "personal" ? "\x1B[32mpersonal\x1B[0m" : "\x1B[34mshared\x1B[0m ";
console.log(` ${key.padEnd(maxLen + 2)}${scope}`);
}
console.log(`
Total: ${keys.length} keys (agent: ${data.agent_id})`);
}
async function cmdFlags(args) {
const shared = args.includes("--shared");
const filtered = args.filter((a) => !["--shared"].includes(a));
if (filtered.length < 1) {
console.error("Usage: cfg flags [--shared] <KEY> [--env|--no-env] [--secret|--no-secret]");
process.exit(1);
}
const key = filtered[0];
const flagArgs = filtered.slice(1);
const body = {};
if (flagArgs.includes("--env")) body.env = true;
if (flagArgs.includes("--no-env")) body.env = false;
if (flagArgs.includes("--secret")) body.secret = true;
if (flagArgs.includes("--no-secret")) body.secret = false;
if (Object.keys(body).length === 0) {
// Just show current flags
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
console.log(`${key}: env=${data.env ?? true}, secret=${data.secret ?? false} (${data.scope})`);
return;
}
const scope = shared ? "shared" : "personal";
const { data } = await api("PATCH", `/config/${encodeURIComponent(key)}?scope=${scope}`, body);
console.log(`${key} flags updated: env=${data.env}, secret=${data.secret}`);
// Update cache
const cache = loadCache();
if (cache && cache.secrets[key]) {
if (body.env !== undefined) cache.secrets[key].env = body.env;
if (body.secret !== undefined) cache.secrets[key].secret = body.secret;
saveCache(cache);
}
}
function showHelp() {
console.log(`cfg — config.shazhou.work CLI
Usage:
cfg sync Fetch all config to local cache
cfg env Output export statements (from cache, auto-syncs if stale)
cfg get <KEY> Read a key (from cache)
cfg get --remote <KEY> Read a key (from server)
cfg set <KEY> <VALUE> Write to personal scope
cfg set --shared <KEY> <VALUE> Write to shared scope (admin only)
cfg set --no-env <KEY> <VALUE> Mark as non-env (won't export via cfg env)
cfg set --secret <KEY> <VALUE> Mark as secret (sensitive, UI masked)
cfg flags <KEY> Show flags for a key
cfg flags <KEY> --no-env Set no-env flag
cfg flags <KEY> --secret Set secret flag
cfg unset <KEY> Delete from personal scope
cfg unset --shared <KEY> Delete from shared scope (admin only)
cfg list List all keys with scope (from cache)
cfg token <TOKEN> Save auth token
Admin:
cfg admin agents List all agents
cfg admin add <ID> [--admin] Create agent token (default role: agent)
cfg admin remove <ID> Revoke all tokens for an agent
cfg admin refresh <ID> Revoke + recreate token
cfg admin inspect <ID> View an agent's resolved config
Auto-sync:
cfg env auto-syncs when cache is stale (>1 day since last success,
or last sync failed and >2 hours since last attempt).
Failed syncs fall back to stale cache silently.
Environment:
CFG_TOKEN Auth token (overrides saved token)
CFG_ENDPOINT API endpoint (default: ${DEFAULT_ENDPOINT})
Shell setup:
eval $(cfg env) Add to .profile / .bashrc / .zshrc`);
}
var [cmd, ...args] = process.argv.slice(2);
switch (cmd) {
case "sync":
await cmdSync();
break;
case "env":
await cmdEnv();
break;
case "get": {
const remote = args.includes("--remote");
const filtered = args.filter((a) => a !== "--remote");
if (!filtered[0]) {
console.error("Usage: cfg get [--remote] <KEY>");
process.exit(1);
}
await cmdGet(filtered[0], remote);
break;
}
case "set":
await cmdSet(args);
break;
case "unset":
await cmdUnset(args);
break;
case "flags":
await cmdFlags(args);
break;
case "list":
await cmdList();
break;
case "token":
if (!args[0]) {
console.error("Usage: cfg token <TOKEN>");
process.exit(1);
}
cmdToken(args[0]);
break;
case "admin": {
const [sub, ...subArgs] = args;
switch (sub) {
case "agents":
await cmdAdminListAgents();
break;
case "add":
await cmdAdminAddUser(subArgs);
break;
case "remove":
await cmdAdminRemoveUser(subArgs);
break;
case "refresh":
await cmdAdminRefreshToken(subArgs);
break;
case "inspect":
await cmdAdminInspect(subArgs);
break;
default:
console.error(`Unknown admin command: ${sub}`);
showHelp();
process.exit(1);
}
break;
}
case "help":
case "--help":
case "-h":
case undefined:
showHelp();
break;
default:
console.error(`Unknown command: ${cmd}`);
showHelp();
process.exit(1);
}

5
package.json Normal file
View File

@ -0,0 +1,5 @@
{
"name": "config-service",
"private": true,
"workspaces": ["packages/*"]
}

1
packages/cfg/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
dist/

17
packages/cfg/package.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "@shazhou/cfg",
"version": "1.3.0",
"type": "module",
"bin": {
"cfg": "./dist/cli.js"
},
"files": ["dist"],
"scripts": {
"build": "bun build src/cli.ts --outfile dist/cli.js --target node --minify && { echo '#!/usr/bin/env node'; cat dist/cli.js; } > dist/cli.tmp && mv dist/cli.tmp dist/cli.js",
"prepublishOnly": "bun run build"
},
"publishConfig": {
"access": "public"
},
"license": "MIT"
}

70
packages/cfg/src/api.ts Normal file
View File

@ -0,0 +1,70 @@
import { getToken, getEndpoint, loadCache, saveCache } from "./config.js";
export async function api(
method: string,
path: string,
body?: unknown
): Promise<{ data: any; status: number }> {
const url = `${getEndpoint()}${path}`;
const headers: Record<string, string> = {
Authorization: `Bearer ${getToken()}`,
"Content-Type": "application/json",
};
let res: Response;
try {
res = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
} catch (err: any) {
console.error(
`Error: ${err?.cause?.message || err?.message || "network error"}`
);
process.exit(1);
}
if (res.status === 204) return { data: null, status: 204 };
const text = await res.text();
let data: any;
try {
data = JSON.parse(text);
} catch {
data = text;
}
if (!res.ok) {
const msg = data?.error || text;
console.error(`Error: ${msg}`);
process.exit(1);
}
return { data, status: res.status };
}
export async function trySyncRemote(): Promise<boolean> {
const url = `${getEndpoint()}/config`;
const headers: Record<string, string> = {
Authorization: `Bearer ${getToken()}`,
"Content-Type": "application/json",
};
try {
const res = await fetch(url, { method: "GET", headers });
if (!res.ok) return false;
const data = await res.json() as any;
if (!data?.secrets) return false;
const now = new Date().toISOString();
const cache = {
agent_id: data.agent_id,
secrets: data.secrets,
synced_at: now,
attempted_at: now,
};
saveCache(cache);
return true;
} catch {
const cache = loadCache();
if (cache) {
cache.attempted_at = new Date().toISOString();
saveCache(cache);
}
return false;
}
}

114
packages/cfg/src/cli.ts Normal file
View File

@ -0,0 +1,114 @@
import {
cmdSync,
cmdEnv,
cmdGet,
cmdSet,
cmdUnset,
cmdFlags,
cmdList,
cmdToken,
cmdAdminAddUser,
cmdAdminRemoveUser,
cmdAdminListAgents,
cmdAdminRefreshToken,
cmdAdminInspect,
cmdProfiles,
cmdProfile,
cmdProfileSet,
cmdProfileUnset,
showSkill,
showHelp,
} from "./commands.js";
const [cmd, ...args] = process.argv.slice(2);
switch (cmd) {
case "sync":
await cmdSync();
break;
case "env":
await cmdEnv();
break;
case "get": {
const remote = args.includes("--remote");
const filtered = args.filter((a) => a !== "--remote");
if (!filtered[0]) {
console.error("Usage: cfg get [--remote] <KEY>");
process.exit(1);
}
await cmdGet(filtered[0], remote);
break;
}
case "set":
await cmdSet(args);
break;
case "unset":
await cmdUnset(args);
break;
case "flags":
await cmdFlags(args);
break;
case "list":
await cmdList();
break;
case "token":
if (!args[0]) {
console.error("Usage: cfg token <TOKEN>");
process.exit(1);
}
cmdToken(args[0]);
break;
case "profiles":
await cmdProfiles();
break;
case "profile": {
const [sub, ...subArgs] = args;
if (sub === "set") {
await cmdProfileSet(subArgs);
} else if (sub === "unset") {
await cmdProfileUnset(subArgs);
} else {
// sub is either an agent_id or undefined (show own)
await cmdProfile(sub);
}
break;
}
case "admin": {
const [sub, ...subArgs] = args;
switch (sub) {
case "agents":
await cmdAdminListAgents();
break;
case "add":
await cmdAdminAddUser(subArgs);
break;
case "remove":
await cmdAdminRemoveUser(subArgs);
break;
case "refresh":
await cmdAdminRefreshToken(subArgs);
break;
case "inspect":
await cmdAdminInspect(subArgs);
break;
default:
console.error(`Unknown admin command: ${sub}`);
showHelp();
process.exit(1);
}
break;
}
case "help":
case "--help":
case "-h":
case undefined:
showHelp();
break;
case "skill":
showSkill(args[0]);
break;
default:
console.error(`Unknown command: ${cmd}`);
showHelp();
process.exit(1);
}

View File

@ -0,0 +1,646 @@
import {
loadConfig,
saveConfig,
loadCache,
saveCache,
ONE_DAY,
TWO_HOURS,
DEFAULT_ENDPOINT,
type Cache,
} from "./config.js";
import { api, trySyncRemote } from "./api.js";
export function shouldAutoSync(cache: Cache | null): boolean {
if (!cache) return true;
const now = Date.now();
const syncedAt = new Date(cache.synced_at).getTime();
const attemptedAt = new Date(cache.attempted_at || cache.synced_at).getTime();
if (syncedAt >= attemptedAt && now - syncedAt < ONE_DAY) {
return false;
}
if (now - attemptedAt < TWO_HOURS) {
return false;
}
return true;
}
export async function cmdSync(): Promise<void> {
const { data } = await api("GET", "/config");
if (!data?.secrets) {
console.error("No secrets found");
process.exit(1);
}
const now = new Date().toISOString();
const cache = {
agent_id: data.agent_id,
secrets: data.secrets,
synced_at: now,
attempted_at: now,
};
saveCache(cache);
const count = Object.keys(cache.secrets).length;
console.log(`✓ Synced ${count} keys (agent: ${cache.agent_id})`);
}
export async function cmdEnv(): Promise<void> {
let cache = loadCache();
if (shouldAutoSync(cache)) {
const ok = await trySyncRemote();
if (ok) {
cache = loadCache();
} else if (!cache) {
console.error("No local cache and sync failed. Run: cfg sync");
process.exit(1);
}
}
for (const [key, entry] of Object.entries(cache!.secrets).sort(([a], [b]) =>
a.localeCompare(b)
)) {
if (entry.env === false) continue;
const escaped = entry.value.replace(/'/g, "'\\''");
console.log(`export ${key}='${escaped}'`);
}
}
export async function cmdGet(key: string, remote: boolean): Promise<void> {
if (remote) {
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
console.log(data.value);
return;
}
let cache = loadCache();
if (shouldAutoSync(cache)) {
const ok = await trySyncRemote();
if (ok) cache = loadCache();
else if (!cache) {
console.error("No local cache and sync failed. Run: cfg sync");
process.exit(1);
}
}
if (!cache) {
console.error("No local cache. Run: cfg sync");
process.exit(1);
}
const entry = cache.secrets[key];
if (!entry) {
console.error(`Error: ${key} not found in cache. Try: cfg sync`);
process.exit(1);
}
console.log(entry.value);
}
export async function cmdSet(args: string[]): Promise<void> {
const shared = args.includes("--shared");
const noEnv = args.includes("--no-env");
const isSecret = args.includes("--secret");
const filtered = args.filter(
(a) => !["--shared", "--no-env", "--secret"].includes(a)
);
if (filtered.length < 2) {
console.error(
"Usage: cfg set [--shared] [--no-env] [--secret] <KEY> <VALUE>"
);
process.exit(1);
}
const [key, ...rest] = filtered;
const value = rest.join(" ");
const scope = shared ? "shared" : "personal";
const body = { value, env: !noEnv, secret: isSecret };
await api("PUT", `/config/${encodeURIComponent(key)}?scope=${scope}`, body);
const flags: string[] = [];
if (noEnv) flags.push("no-env");
if (isSecret) flags.push("secret");
const flagStr = flags.length ? ` [${flags.join(", ")}]` : "";
console.log(`${key} (${scope})${flagStr}`);
const cache = loadCache();
if (cache) {
cache.secrets[key] = {
value,
scope,
env: !noEnv,
secret: isSecret,
updated_at: new Date().toISOString(),
};
saveCache(cache);
}
}
export async function cmdUnset(args: string[]): Promise<void> {
const shared = args.includes("--shared");
const filtered = args.filter((a) => a !== "--shared");
if (filtered.length < 1) {
console.error("Usage: cfg unset [--shared] <KEY>");
process.exit(1);
}
const key = filtered[0];
const scope = shared ? "shared" : "personal";
await api("DELETE", `/config/${encodeURIComponent(key)}?scope=${scope}`);
console.log(`✓ Deleted ${key} (${scope})`);
const cache = loadCache();
if (cache && cache.secrets[key]) {
delete cache.secrets[key];
saveCache(cache);
}
}
export async function cmdList(): Promise<void> {
let cache = loadCache();
if (shouldAutoSync(cache)) {
const ok = await trySyncRemote();
if (ok) cache = loadCache();
else if (!cache) {
console.error("No local cache and sync failed. Run: cfg sync");
process.exit(1);
}
}
if (!cache) {
console.error("No local cache. Run: cfg sync");
process.exit(1);
}
if (!cache.secrets || Object.keys(cache.secrets).length === 0) {
console.log("No keys found");
return;
}
const keys = Object.keys(cache.secrets).sort();
const maxLen = Math.max(...keys.map((k) => k.length));
for (const key of keys) {
const entry = cache.secrets[key];
const scope =
entry.scope === "personal"
? "\x1B[32mpersonal\x1B[0m"
: "\x1B[34mshared\x1B[0m ";
const flags: string[] = [];
if (entry.env === false) flags.push("\x1B[33mno-env\x1B[0m");
if (entry.secret) flags.push("\x1B[31msecret\x1B[0m");
const flagStr = flags.length ? " " + flags.join(" ") : "";
console.log(` ${key.padEnd(maxLen + 2)}${scope}${flagStr}`);
}
console.log(`\nTotal: ${keys.length} keys (agent: ${cache.agent_id})`);
console.log(`Last sync: ${cache.synced_at}`);
}
export function cmdToken(token: string): void {
const cfg = loadConfig();
cfg.token = token;
saveConfig(cfg);
console.log("✓ Token saved");
}
export async function cmdFlags(args: string[]): Promise<void> {
const shared = args.includes("--shared");
const filtered = args.filter((a) => !["--shared"].includes(a));
if (filtered.length < 1) {
console.error(
"Usage: cfg flags [--shared] <KEY> [--env|--no-env] [--secret|--no-secret]"
);
process.exit(1);
}
const key = filtered[0];
const flagArgs = filtered.slice(1);
const body: Record<string, boolean> = {};
if (flagArgs.includes("--env")) body.env = true;
if (flagArgs.includes("--no-env")) body.env = false;
if (flagArgs.includes("--secret")) body.secret = true;
if (flagArgs.includes("--no-secret")) body.secret = false;
if (Object.keys(body).length === 0) {
// Just show current flags
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
console.log(
`${key}: env=${data.env ?? true}, secret=${data.secret ?? false} (${data.scope})`
);
return;
}
const scope = shared ? "shared" : "personal";
const { data } = await api(
"PATCH",
`/config/${encodeURIComponent(key)}?scope=${scope}`,
body
);
console.log(`${key} flags updated: env=${data.env}, secret=${data.secret}`);
// Update cache
const cache = loadCache();
if (cache && cache.secrets[key]) {
if (body.env !== undefined) cache.secrets[key].env = body.env;
if (body.secret !== undefined) cache.secrets[key].secret = body.secret;
saveCache(cache);
}
}
export async function cmdAdminAddUser(args: string[]): Promise<void> {
const role = args.includes("--admin") ? "admin" : "agent";
const filtered = args.filter((a) => a !== "--admin");
if (!filtered[0]) {
console.error("Usage: cfg admin add <AGENT_ID> [--admin]");
process.exit(1);
}
const { data } = await api("POST", "/admin/token", {
agent_id: filtered[0],
role,
});
console.log(`✓ Created ${data.role} token for ${data.agent_id}`);
console.log(` Token: ${data.token}`);
}
export async function cmdAdminRemoveUser(args: string[]): Promise<void> {
if (!args[0]) {
console.error("Usage: cfg admin remove <AGENT_ID>");
process.exit(1);
}
const { data } = await api(
"DELETE",
`/admin/token/${encodeURIComponent(args[0])}`
);
console.log(`✓ Revoked ${data.tokens_revoked} token(s) for ${data.agent_id}`);
}
export async function cmdAdminListAgents(): Promise<void> {
const { data } = await api("GET", "/admin/agents");
if (!data.agents?.length) {
console.log("No agents found");
return;
}
console.log("Agents:");
for (const agent of data.agents) {
console.log(` ${agent}`);
}
}
export async function cmdAdminRefreshToken(args: string[]): Promise<void> {
if (!args[0]) {
console.error("Usage: cfg admin refresh <AGENT_ID>");
process.exit(1);
}
const agentId = args[0];
await api("DELETE", `/admin/token/${encodeURIComponent(agentId)}`);
const { data } = await api("POST", "/admin/token", { agent_id: agentId });
console.log(`✓ Refreshed token for ${data.agent_id}`);
console.log(` Token: ${data.token}`);
}
export async function cmdAdminInspect(args: string[]): Promise<void> {
if (!args[0]) {
console.error("Usage: cfg admin inspect <AGENT_ID>");
process.exit(1);
}
const { data } = await api(
"GET",
`/admin/agent/${encodeURIComponent(args[0])}`
);
if (!data.secrets || Object.keys(data.secrets).length === 0) {
console.log(`No keys for ${data.agent_id}`);
return;
}
const keys = Object.keys(data.secrets).sort();
const maxLen = Math.max(...keys.map((k) => k.length));
for (const key of keys) {
const entry = data.secrets[key];
const scope =
entry.scope === "personal"
? "\x1B[32mpersonal\x1B[0m"
: "\x1B[34mshared\x1B[0m ";
console.log(` ${key.padEnd(maxLen + 2)}${scope}`);
}
console.log(`\nTotal: ${keys.length} keys (agent: ${data.agent_id})`);
}
// ── Profile commands ──────────────────────────────────────────────────
export async function cmdProfiles(): Promise<void> {
const { data } = await api("GET", "/profiles");
if (!data.agents?.length) {
console.log("No agents with public profiles");
return;
}
console.log("Agents with public profiles:");
for (const agent of data.agents) {
console.log(` ${agent}`);
}
}
export async function cmdProfile(agentId?: string): Promise<void> {
// If no agent specified, show own profile — need to know own agent_id
const path = agentId
? `/profile/${encodeURIComponent(agentId)}`
: (() => {
const cache = loadCache();
if (cache?.agent_id) return `/profile/${encodeURIComponent(cache.agent_id)}`;
return null;
})();
if (!path) {
console.error("Cannot determine your agent_id. Run: cfg sync");
process.exit(1);
}
const { data } = await api("GET", path);
if (!data.profile || Object.keys(data.profile).length === 0) {
console.log(`No public profile for ${data.agent_id}`);
return;
}
const keys = Object.keys(data.profile).sort();
const maxLen = Math.max(...keys.map((k) => k.length));
console.log(`Profile: ${data.agent_id}`);
for (const key of keys) {
const entry = data.profile[key];
console.log(` ${key.padEnd(maxLen + 2)}${entry.value}`);
}
}
export async function cmdProfileSet(args: string[]): Promise<void> {
if (args.length < 2) {
console.error("Usage: cfg profile set <KEY> <VALUE>");
process.exit(1);
}
const [key, ...rest] = args;
const value = rest.join(" ");
// Need own agent_id for the PUT path
let agentId: string | undefined;
const cache = loadCache();
if (cache?.agent_id) {
agentId = cache.agent_id;
} else {
// Try sync to get agent_id
const ok = await trySyncRemote();
if (ok) {
const c = loadCache();
agentId = c?.agent_id;
}
}
if (!agentId) {
console.error("Cannot determine your agent_id. Run: cfg sync");
process.exit(1);
}
await api("PUT", `/profile/${encodeURIComponent(agentId)}/${encodeURIComponent(key)}`, { value });
console.log(`${key} set in public profile`);
}
export async function cmdProfileUnset(args: string[]): Promise<void> {
if (!args[0]) {
console.error("Usage: cfg profile unset <KEY>");
process.exit(1);
}
const key = args[0];
let agentId: string | undefined;
const cache = loadCache();
if (cache?.agent_id) {
agentId = cache.agent_id;
} else {
const ok = await trySyncRemote();
if (ok) {
const c = loadCache();
agentId = c?.agent_id;
}
}
if (!agentId) {
console.error("Cannot determine your agent_id. Run: cfg sync");
process.exit(1);
}
await api("DELETE", `/profile/${encodeURIComponent(agentId)}/${encodeURIComponent(key)}`);
console.log(`${key} deleted from public profile`);
}
export function showSkill(topic?: string): void {
const topics: Record<string, string> = {
general: `# cfg — General Usage
cfg is the CLI for config.shazhou.work centralized config & secret management
for the agent network. Built on Cloudflare Workers + KV.
## Concepts
- **Scopes**: shared (admin-only write, all read) and personal (own agent read/write)
- **Resolution**: personal overrides shared (personal > shared fallback)
- **Caching**: local cache with auto-sync (fresh 1 day, retry 2h after failure)
- **Profile**: public key-value pairs visible to all agents, writable only by owner
## Shell Setup
eval $(cfg env) Add to .bashrc / .zshrc / .profile
## Commands
cfg get <KEY> Read from cache (auto-syncs if stale)
cfg get --remote <KEY> Read directly from server
cfg set <KEY> <VALUE> Write to personal scope
cfg set --shared <KEY> <VALUE> Write to shared scope (admin only)
cfg set --secret <KEY> <VALUE> Mark as secret (masked in UI)
cfg set --no-env <KEY> <VALUE> Won't be exported by cfg env
cfg unset <KEY> Delete from personal scope
cfg unset --shared <KEY> Delete from shared scope (admin only)
cfg list List all keys with scope/flags
cfg sync Force sync from server
cfg env Output export statements for shell
cfg flags <KEY> [--env|--no-env] [--secret|--no-secret]
cfg profile Show your own public profile
cfg profile <AGENT_ID> Show another agent's public profile
cfg profile set <KEY> <VALUE> Set a key in your public profile
cfg profile unset <KEY> Delete a key from your public profile
cfg profiles List all agents with public profiles
cfg token <TOKEN> Save auth token locally
## Environment Variables
CFG_TOKEN Auth token (overrides saved token)
CFG_ENDPOINT API endpoint (default: https://config.shazhou.work)
## Tips
- Use --secret for API keys, tokens masked in the web UI
- Use --no-env for config that shouldn't pollute the shell environment
- Profile is great for contact info, roles, and public metadata
- Cache lives at ~/.config/cfg/cache.json`,
contract: `# cfg — API Contract
Base URL: https://config.shazhou.work
Auth: Bearer token in Authorization header
## KV Storage Layout
auth:{sha256(token)} { agent_id, role }
agent_tokens:{agent_id} [hash1, hash2, ...]
shared:{key} { value, updated_at, env, secret }
personal:{agent_id}:{key} { value, updated_at, env, secret }
public:{agent_id}:{key} { value, updated_at, env: false, secret: false }
## Config Endpoints (auth required)
GET /config List/sync all resolved keys
?scope=shared|personal to filter
GET /config/:key Read key (personal > shared fallback)
PUT /config/:key?scope=personal Write key
?scope=shared (admin only)
Body: { value, env?, secret? }
PATCH /config/:key?scope=... Update flags only (env, secret)
Body: { env?, secret? }
DELETE /config/:key?scope=... Delete key
POST /config/sync Full sync all resolved key-values
## Profile Endpoints (auth required)
GET /profiles List agent_ids with public profiles
GET /profile/:agent_id All public keys for an agent
GET /profile/:agent_id/:key Single public key
PUT /profile/:agent_id/:key Set (own profile only, 403 otherwise)
Body: { value }
DELETE /profile/:agent_id/:key Delete (own profile only)
## Admin Endpoints (admin role required)
GET /admin/agents List all registered agents
POST /admin/token Create token
Body: { agent_id, role? }
Returns: { agent_id, role, token }
DELETE /admin/token/:agent_id Revoke all tokens for agent
GET /admin/agent/:agent_id Inspect agent's resolved config
## Public Endpoints (no auth)
GET /health { status: "ok" }
GET / Web UI (HTML)
## Response Format
Success: { key, value, scope, env, secret, updated_at }
Error: { error: "message" } with appropriate HTTP status
Sync: { agent_id, role, secrets: { key: { value, scope, env, secret, updated_at } } }
## Auth Flow
1. Admin creates token via POST /admin/token returns raw token
2. Agent stores token via \`cfg token <TOKEN>\`
3. All requests include Authorization: Bearer <token>
4. Server hashes token with SHA-256, looks up auth:{hash} in KV`,
onboarding: `# cfg — Agent Onboarding
Step-by-step guide for new agents joining the network.
## Prerequisites
- Node.js 18+ or Bun installed
- An agent token (ask an admin to run: cfg admin add <your_id>)
## Step 1: Install cfg
bun install -g @shazhou/cfg
# or: npm install -g @shazhou/cfg
## Step 2: Save your token
cfg token <YOUR_TOKEN>
## Step 3: First sync
cfg sync
# Should show: Synced N keys (agent: your_id)
## Step 4: Set up shell integration
Add to your .bashrc / .zshrc / .profile:
export PATH="$HOME/.bun/bin:$PATH"
eval $(cfg env)
Then reload: source ~/.bashrc
## Step 5: Verify
cfg list # See all your keys
cfg get GITEA_ADMIN_TOKEN # Test reading a shared key
## Step 6: Set up your public profile
cfg profile set role "你的角色描述"
cfg profile set contact "telegram:your_handle"
cfg profile set github "your_github"
## Step 7: Check others' profiles
cfg profiles # List all agents
cfg profile tuanzi # See tuanzi's profile
## Troubleshooting
- "unauthorized" token is wrong or revoked, ask admin for a new one
- "No local cache" run cfg sync first
- Network errors check proxy settings, config.shazhou.work uses Cloudflare`,
admin: `# cfg — Admin Operations
Admin commands require a token with role: admin.
## User Management
cfg admin agents List all registered agents
cfg admin add <ID> Create agent token (role: agent)
cfg admin add <ID> --admin Create admin token
cfg admin remove <ID> Revoke ALL tokens for an agent
cfg admin refresh <ID> Revoke + create new token (rotate)
cfg admin inspect <ID> View agent's full resolved config
## Shared Config Management
cfg set --shared <KEY> <VALUE> Write to shared scope
cfg unset --shared <KEY> Delete from shared scope
cfg flags <KEY> --shared --secret Set shared key as secret
## Onboarding a New Agent
1. cfg admin add <agent_id>
2. Send the token to the agent securely
3. Agent runs: cfg token <TOKEN> && cfg sync
4. Agent sets up: eval $(cfg env) in shell
## Offboarding / Security Isolation
1. cfg admin remove <agent_id> # Revoke all tokens
2. Agent can no longer access any config
3. Their personal config remains in KV but is inaccessible
## Inspecting an Agent
cfg admin inspect <agent_id>
# Shows all resolved keys (shared + personal overrides)
# Useful for debugging "why can't agent X see key Y"
## Token Rotation
cfg admin refresh <agent_id>
# Old token immediately invalid, new token printed
# Agent must run: cfg token <NEW_TOKEN>`,
};
if (!topic || topic === "general") {
console.log(topics.general);
console.log(`\n## Other Skills`);
console.log(` cfg skill contract API endpoints, KV layout, request/response format`);
console.log(` cfg skill onboarding New agent setup guide`);
console.log(` cfg skill admin Admin operations & user management`);
} else if (topics[topic]) {
console.log(topics[topic]);
} else {
console.error(`Unknown skill topic: ${topic}`);
console.log(`Available: general (default), contract, onboarding, admin`);
process.exit(1);
}
}
export function showHelp(): void {
console.log(`cfg — config.shazhou.work CLI
Usage:
cfg sync Fetch all config to local cache
cfg env Output export statements (from cache, auto-syncs if stale)
cfg get <KEY> Read a key (from cache)
cfg get --remote <KEY> Read a key (from server)
cfg set <KEY> <VALUE> Write to personal scope
cfg set --shared <KEY> <VALUE> Write to shared scope (admin only)
cfg set --no-env <KEY> <VALUE> Mark as non-env (won't export via cfg env)
cfg set --secret <KEY> <VALUE> Mark as secret (sensitive, UI masked)
cfg flags <KEY> Show flags for a key
cfg flags <KEY> --no-env Set no-env flag
cfg flags <KEY> --secret Set secret flag
cfg unset <KEY> Delete from personal scope
cfg unset --shared <KEY> Delete from shared scope (admin only)
cfg list List all keys with scope (from cache)
cfg token <TOKEN> Save auth token
Profile (public, readable by all agents):
cfg profile Show your own public profile
cfg profile <AGENT_ID> Show another agent's public profile
cfg profile set <KEY> <VALUE> Set a key in your public profile
cfg profile unset <KEY> Delete a key from your public profile
cfg profiles List all agents with public profiles
Admin:
cfg admin agents List all agents
cfg admin add <ID> [--admin] Create agent token (default role: agent)
cfg admin remove <ID> Revoke all tokens for an agent
cfg admin refresh <ID> Revoke + recreate token
cfg admin inspect <ID> View an agent's resolved config
Auto-sync:
cfg env auto-syncs when cache is stale (>1 day since last success,
or last sync failed and >2 hours since last attempt).
Failed syncs fall back to stale cache silently.
Environment:
CFG_TOKEN Auth token (overrides saved token)
CFG_ENDPOINT API endpoint (default: ${DEFAULT_ENDPOINT})
Shell setup:
eval $(cfg env) Add to .profile / .bashrc / .zshrc`);
}

View File

@ -0,0 +1,73 @@
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
import { homedir } from "os";
export const CONFIG_DIR = join(homedir(), ".config", "cfg");
export const CONFIG_FILE = join(CONFIG_DIR, "config.json");
export const CACHE_FILE = join(CONFIG_DIR, "cache.json");
export const DEFAULT_ENDPOINT = "https://config.shazhou.work";
export const ONE_DAY = 24 * 60 * 60 * 1000;
export const TWO_HOURS = 2 * 60 * 60 * 1000;
export interface Config {
token?: string;
endpoint?: string;
[key: string]: unknown;
}
export interface SecretEntry {
value: string;
scope?: string;
env?: boolean;
secret?: boolean;
updated_at?: string;
[key: string]: unknown;
}
export interface Cache {
agent_id: string;
secrets: Record<string, SecretEntry>;
synced_at: string;
attempted_at: string;
}
export function loadConfig(): Config {
try {
return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
} catch {
return {};
}
}
export function saveConfig(cfg: Config): void {
mkdirSync(CONFIG_DIR, { recursive: true });
writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n");
}
export function loadCache(): Cache | null {
try {
return JSON.parse(readFileSync(CACHE_FILE, "utf-8"));
} catch {
return null;
}
}
export function saveCache(cache: Cache): void {
mkdirSync(CONFIG_DIR, { recursive: true });
writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2) + "\n");
}
export function getToken(): string {
const cfg = loadConfig();
const token = process.env.CFG_TOKEN || cfg.token;
if (!token) {
console.error("No token configured. Run: cfg token <TOKEN>");
process.exit(1);
}
return token;
}
export function getEndpoint(): string {
const cfg = loadConfig();
return cfg.endpoint || process.env.CFG_ENDPOINT || DEFAULT_ENDPOINT;
}

View File

@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}

24
packages/webui/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
packages/webui/README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

12
packages/webui/index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Config Service</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,35 @@
{
"name": "webui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"lucide-react": "^1.8.0",
"react": "^19.2.5",
"react-dom": "^19.2.5"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/vite": "^4.2.3",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"tailwindcss": "^4.2.3",
"terser": "^5.46.1",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.9",
"vite-plugin-singlefile": "^2.3.3"
}
}

View File

@ -0,0 +1,34 @@
import { useState, useCallback } from "react";
import LoginPage from "./components/LoginPage";
import Dashboard from "./components/Dashboard";
import Toast from "./components/Toast";
import type { Toast as ToastType } from "./types";
export default function App() {
const [authed, setAuthed] = useState(!!localStorage.getItem("config-token"));
const [toasts, setToasts] = useState<ToastType[]>([]);
const addToast = useCallback((message: string, type: "success" | "error") => {
setToasts((prev) => [...prev, { id: Date.now() + Math.random(), message, type }]);
}, []);
const removeToast = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const logout = () => {
localStorage.removeItem("config-token");
setAuthed(false);
};
return (
<>
<Toast toasts={toasts} remove={removeToast} />
{authed ? (
<Dashboard onLogout={logout} addToast={addToast} />
) : (
<LoginPage onLogin={() => setAuthed(true)} />
)}
</>
);
}

View File

@ -0,0 +1,90 @@
import { useState } from "react";
import type { ConfigEntry } from "../types";
interface Props {
editKey?: string;
editEntry?: ConfigEntry;
onSave: (key: string, value: string, scope: string, env: boolean, secret: boolean) => void;
onClose: () => void;
}
export default function AddEditModal({ editKey, editEntry, onSave, onClose }: Props) {
const [key, setKey] = useState(editKey || "");
const [value, setValue] = useState(editEntry?.value || "");
const [scope, setScope] = useState(editEntry?.scope || "personal");
const [excludeEnv, setExcludeEnv] = useState(editEntry ? !editEntry.env : false);
const [secret, setSecret] = useState(editEntry?.secret || false);
const isEdit = !!editKey;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSave(key, value, scope, !excludeEnv, secret);
};
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 backdrop-blur-sm" onClick={onClose}>
<form
onClick={(e) => e.stopPropagation()}
onSubmit={handleSubmit}
className="w-full max-w-lg bg-[#12141a] border border-[#1e2030] rounded-2xl p-6 shadow-2xl"
>
<h2 className="text-xl font-bold text-white mb-6" style={{ fontFamily: "var(--font-heading)" }}>
{isEdit ? "Edit Key" : "Add Key"}
</h2>
<label className="block text-sm text-[#64748b] mb-1 font-medium">Key</label>
<input
value={key}
onChange={(e) => setKey(e.target.value)}
disabled={isEdit}
className="w-full px-3 py-2 mb-4 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white disabled:opacity-50 focus:outline-none focus:border-[#3b82f6] transition-colors"
style={{ fontFamily: "var(--font-mono)" }}
placeholder="MY_CONFIG_KEY"
required
/>
<label className="block text-sm text-[#64748b] mb-1 font-medium">Value</label>
<textarea
value={value}
onChange={(e) => setValue(e.target.value)}
rows={4}
className="w-full px-3 py-2 mb-4 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white resize-none focus:outline-none focus:border-[#3b82f6] transition-colors"
style={{ fontFamily: "var(--font-mono)" }}
placeholder="value"
required
/>
<label className="block text-sm text-[#64748b] mb-1 font-medium">Scope</label>
<select
value={scope}
onChange={(e) => setScope(e.target.value as "personal" | "shared")}
className="w-full px-3 py-2 mb-4 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white focus:outline-none focus:border-[#3b82f6]"
>
<option value="personal">Personal</option>
<option value="shared">Shared</option>
</select>
<div className="flex flex-col gap-3 mb-6">
<label className="flex items-center gap-2 text-sm text-[#e2e8f0] cursor-pointer">
<input type="checkbox" checked={excludeEnv} onChange={(e) => setExcludeEnv(e.target.checked)} className="accent-[#eab308]" />
Exclude from env export
</label>
<label className="flex items-center gap-2 text-sm text-[#e2e8f0] cursor-pointer">
<input type="checkbox" checked={secret} onChange={(e) => setSecret(e.target.checked)} className="accent-[#ef4444]" />
Mark as secret
</label>
</div>
<div className="flex justify-end gap-3">
<button type="button" onClick={onClose} className="px-4 py-2 text-sm text-[#64748b] hover:text-white transition-colors">
Cancel
</button>
<button type="submit" className="px-5 py-2 bg-[#3b82f6] hover:bg-[#2563eb] text-white text-sm font-semibold rounded-lg transition-colors">
{isEdit ? "Update" : "Create"}
</button>
</div>
</form>
</div>
);
}

View File

@ -0,0 +1,114 @@
import { useEffect, useState } from "react";
import { useApi } from "../hooks/useApi";
import type { Agent } from "../types";
interface Props {
addToast: (msg: string, type: "success" | "error") => void;
}
export default function AdminPanel({ addToast }: Props) {
const api = useApi();
const [agents, setAgents] = useState<Agent[]>([]);
const [newAgentId, setNewAgentId] = useState("");
const [newRole, setNewRole] = useState("agent");
const [generatedToken, setGeneratedToken] = useState("");
const [loading, setLoading] = useState(true);
const loadAgents = async () => {
try {
const data = await api.getAgents();
setAgents(Array.isArray(data) ? data : data.agents || []);
} catch (e: any) {
addToast("Failed to load agents: " + e.message, "error");
} finally {
setLoading(false);
}
};
useEffect(() => { loadAgents(); }, []);
const handleCreateToken = async () => {
if (!newAgentId.trim()) return;
try {
const data = await api.createToken(newAgentId.trim(), newRole);
setGeneratedToken(data.token || JSON.stringify(data));
addToast("Token created", "success");
setNewAgentId("");
loadAgents();
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
const handleRevoke = async (tokenId: string) => {
try {
await api.revokeToken(tokenId);
addToast("Token revoked", "success");
loadAgents();
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
if (loading) return <div className="text-[#64748b] text-center py-8">Loading agents...</div>;
return (
<div className="space-y-6">
<div className="bg-[#12141a] border border-[#1e2030] rounded-xl p-6">
<h3 className="text-lg font-bold text-white mb-4" style={{ fontFamily: "var(--font-heading)" }}>Create Agent Token</h3>
<div className="flex gap-3 items-end flex-wrap">
<div>
<label className="block text-xs text-[#64748b] mb-1">Agent ID</label>
<input value={newAgentId} onChange={(e) => setNewAgentId(e.target.value)} placeholder="agent-name"
className="px-3 py-2 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white text-sm focus:outline-none focus:border-[#3b82f6]" style={{ fontFamily: "var(--font-mono)" }} />
</div>
<div>
<label className="block text-xs text-[#64748b] mb-1">Role</label>
<select value={newRole} onChange={(e) => setNewRole(e.target.value)}
className="px-3 py-2 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white text-sm focus:outline-none focus:border-[#3b82f6]">
<option value="agent">Agent</option>
<option value="admin">Admin</option>
</select>
</div>
<button onClick={handleCreateToken} className="px-4 py-2 bg-[#3b82f6] hover:bg-[#2563eb] text-white text-sm font-semibold rounded-lg transition-colors">
Generate Token
</button>
</div>
{generatedToken && (
<div className="mt-4 p-3 bg-[#0a0a0c] border border-green-500/30 rounded-lg">
<p className="text-xs text-green-400 mb-1">Generated token (copy now, shown once):</p>
<code className="text-sm text-white break-all" style={{ fontFamily: "var(--font-mono)" }}>{generatedToken}</code>
<button onClick={() => { navigator.clipboard.writeText(generatedToken); addToast("Copied", "success"); }}
className="ml-2 text-xs text-[#3b82f6] hover:underline">Copy</button>
</div>
)}
</div>
<div className="bg-[#12141a] border border-[#1e2030] rounded-xl p-6">
<h3 className="text-lg font-bold text-white mb-4" style={{ fontFamily: "var(--font-heading)" }}>Agents</h3>
{agents.length === 0 ? (
<p className="text-[#64748b] text-sm">No agents found</p>
) : (
<div className="space-y-3">
{agents.map((agent) => (
<div key={agent.id} className="flex items-center justify-between p-3 bg-[#0a0a0c] rounded-lg border border-[#1e2030]">
<div className="flex items-center gap-3">
<span className="text-white font-medium" style={{ fontFamily: "var(--font-mono)" }}>{agent.id}</span>
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
agent.role === "admin" ? "bg-purple-500/15 text-purple-400 border border-purple-500/30" : "bg-[#1e2030] text-[#64748b]"
}`}>{agent.role}</span>
</div>
{agent.tokens?.map((t) => (
<button key={t.id} onClick={() => handleRevoke(t.id)}
className="text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10 px-2 py-1 rounded transition-colors">
Revoke {t.id.slice(0, 8)}...
</button>
))}
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,119 @@
import { useState } from "react";
import type { ConfigEntry } from "../types";
interface Props {
entries: [string, ConfigEntry][];
onEdit: (key: string, entry: ConfigEntry) => void;
onDelete: (key: string, scope: string) => void;
addToast: (msg: string, type: "success" | "error") => void;
}
export default function ConfigTable({ entries, onEdit, onDelete, addToast }: Props) {
const [revealed, setRevealed] = useState<Set<string>>(new Set());
const toggle = (key: string) => {
setRevealed((prev) => {
const next = new Set(prev);
next.has(key) ? next.delete(key) : next.add(key);
return next;
});
};
const copy = (value: string) => {
navigator.clipboard.writeText(value);
addToast("Copied to clipboard", "success");
};
const fmtTime = (iso: string) => {
try {
const d = new Date(iso);
return d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " " + d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
} catch { return iso; }
};
if (entries.length === 0) {
return (
<div className="text-center py-16 text-[#64748b]">
<p className="text-lg mb-1">No configuration keys found</p>
<p className="text-sm">Add your first key to get started</p>
</div>
);
}
return (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-[#64748b] text-xs uppercase tracking-wider border-b border-[#1e2030]">
<th className="pb-3 pr-4 font-medium">Key</th>
<th className="pb-3 pr-4 font-medium">Value</th>
<th className="pb-3 pr-4 font-medium">Scope</th>
<th className="pb-3 pr-4 font-medium">Flags</th>
<th className="pb-3 pr-4 font-medium">Updated</th>
<th className="pb-3 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody>
{entries.map(([key, entry]) => {
const isSecret = entry.secret === true;
const show = !isSecret || revealed.has(key);
const displayVal = show ? entry.value : "•".repeat(Math.min(entry.value.length || 8, 24));
return (
<tr key={key} className="border-b border-[#1e2030]/50 hover:bg-[#1e2030]/30 transition-colors">
<td className="py-3 pr-4" style={{ fontFamily: "var(--font-mono)" }}>
<span className="text-white font-medium">{key}</span>
</td>
<td className="py-3 pr-4 max-w-[280px]">
<div className="flex items-center gap-2">
<span
className={`truncate ${show ? "text-white" : "text-[#64748b]"}`}
style={{ fontFamily: "var(--font-mono)", fontSize: "0.8rem" }}
>
{displayVal}
</span>
{isSecret && (
<button onClick={() => toggle(key)} className="text-[#64748b] hover:text-white shrink-0 transition-colors" title={show ? "Hide" : "Reveal"}>
{show ? "👁" : "👁‍🗨"}
</button>
)}
<button onClick={() => copy(entry.value)} className="text-[#64748b] hover:text-[#3b82f6] shrink-0 transition-colors" title="Copy">
📋
</button>
</div>
</td>
<td className="py-3 pr-4">
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
entry.scope === "shared" ? "bg-blue-500/15 text-blue-400 border border-blue-500/30" : "bg-green-500/15 text-green-400 border border-green-500/30"
}`}>
{entry.scope}
</span>
</td>
<td className="py-3 pr-4">
<div className="flex gap-1.5">
{entry.secret && (
<span className="text-xs px-2 py-0.5 rounded-full bg-red-500/15 text-red-400 border border-red-500/30 font-medium">secret</span>
)}
{entry.env === false && (
<span className="text-xs px-2 py-0.5 rounded-full bg-yellow-500/15 text-yellow-400 border border-yellow-500/30 font-medium">no-env</span>
)}
</div>
</td>
<td className="py-3 pr-4 text-[#64748b] text-xs whitespace-nowrap">{fmtTime(entry.updated_at)}</td>
<td className="py-3 text-right">
<div className="flex justify-end gap-1">
<button onClick={() => onEdit(key, entry)} className="px-2 py-1 text-xs text-[#64748b] hover:text-white hover:bg-[#1e2030] rounded transition-colors">
Edit
</button>
<button onClick={() => onDelete(key, entry.scope)} className="px-2 py-1 text-xs text-[#64748b] hover:text-red-400 hover:bg-red-500/10 rounded transition-colors">
Delete
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

View File

@ -0,0 +1,200 @@
import { useCallback, useEffect, useState } from "react";
import { useApi } from "../hooks/useApi";
import type { ConfigEntry, ConfigResponse } from "../types";
import ConfigTable from "./ConfigTable";
import AddEditModal from "./AddEditModal";
import AdminPanel from "./AdminPanel";
interface Props {
onLogout: () => void;
addToast: (msg: string, type: "success" | "error") => void;
}
export default function Dashboard({ onLogout, addToast }: Props) {
const api = useApi();
const [data, setData] = useState<ConfigResponse | null>(null);
const [search, setSearch] = useState("");
const [scopeFilter, setScopeFilter] = useState<"all" | "personal" | "shared">("all");
const [modal, setModal] = useState<{ key?: string; entry?: ConfigEntry } | null>(null);
const [tab, setTab] = useState<"config" | "admin">("config");
const [loading, setLoading] = useState(true);
const [agentList, setAgentList] = useState<string[]>([]);
const [selectedAgent, setSelectedAgent] = useState<string>("");
const [ownAgentId, setOwnAgentId] = useState<string>("");
const load = useCallback(async (agentId?: string) => {
try {
if (agentId && agentId !== ownAgentId) {
const d = await api.getAgent(agentId);
setData(d);
} else {
const d = await api.getConfig();
setData(d);
if (!ownAgentId && d.agent_id) {
setOwnAgentId(d.agent_id);
setSelectedAgent(d.agent_id);
}
// Load agent list for admins
if (d.role === "admin" && agentList.length === 0) {
try {
const agents = await api.getAgents();
const list = Array.isArray(agents) ? agents : agents.agents || [];
setAgentList(list);
} catch {}
}
}
} catch (e: any) {
addToast("Failed to load: " + e.message, "error");
if (e.message.includes("401") || e.message.includes("403")) onLogout();
} finally {
setLoading(false);
}
}, [ownAgentId, agentList.length]);
useEffect(() => { load(); }, [load]);
const entries = data ? Object.entries(data.secrets || {}) : [];
const filtered = entries.filter(([key, entry]) => {
if (search && !key.toLowerCase().includes(search.toLowerCase())) return false;
if (scopeFilter !== "all" && entry.scope !== scopeFilter) return false;
return true;
});
const handleSave = async (key: string, value: string, scope: string, env: boolean, secret: boolean) => {
try {
await api.putKey(key, scope, { value, env, secret });
addToast(`Key "${key}" saved`, "success");
setModal(null);
load(selectedAgent);
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
const handleDelete = async (key: string, scope: string) => {
if (!confirm(`Delete "${key}"?`)) return;
try {
await api.deleteKey(key, scope);
addToast(`Key "${key}" deleted`, "success");
load(selectedAgent);
} catch (e: any) {
addToast("Failed: " + e.message, "error");
}
};
const handleAgentSwitch = (agentId: string) => {
setSelectedAgent(agentId);
setLoading(true);
load(agentId);
};
const isAdmin = data?.role === "admin";
const isViewingOther = selectedAgent && selectedAgent !== ownAgentId;
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-[#64748b]">Loading...</div>
</div>
);
}
return (
<div className="min-h-screen bg-[#0a0a0c]">
{/* Header */}
<header className="border-b border-[#1e2030] bg-[#12141a]/80 backdrop-blur-sm sticky top-0 z-30">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<h1 className="text-xl font-bold text-white" style={{ fontFamily: "var(--font-heading)" }}>Config Service</h1>
{isAdmin && (
<div className="flex bg-[#0a0a0c] rounded-lg p-0.5 border border-[#1e2030]">
<button onClick={() => setTab("config")} className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${tab === "config" ? "bg-[#3b82f6] text-white" : "text-[#64748b] hover:text-white"}`}>Config</button>
<button onClick={() => setTab("admin")} className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${tab === "admin" ? "bg-[#3b82f6] text-white" : "text-[#64748b] hover:text-white"}`}>Admin</button>
</div>
)}
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-[#64748b]" style={{ fontFamily: "var(--font-mono)" }}>{data?.agent_id}</span>
{isAdmin && agentList.length > 0 && (
<select
value={selectedAgent}
onChange={(e) => handleAgentSwitch(e.target.value)}
className="px-2 py-1 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-sm text-white focus:outline-none focus:border-[#3b82f6] transition-colors"
>
{agentList.map((id) => (
<option key={id} value={id}>{id}{id === ownAgentId ? " (me)" : ""}</option>
))}
</select>
)}
{isViewingOther && <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/15 text-amber-400 border border-amber-500/30 font-medium">viewing {selectedAgent}</span>}
{isAdmin && <span className="text-xs px-2 py-0.5 rounded-full bg-purple-500/15 text-purple-400 border border-purple-500/30 font-medium">admin</span>}
<button onClick={onLogout} className="text-sm text-[#64748b] hover:text-white transition-colors">Logout</button>
</div>
</div>
</header>
<main className="max-w-7xl mx-auto px-6 py-6">
{tab === "config" ? (
<>
{/* Toolbar */}
<div className="flex items-center gap-3 mb-6 flex-wrap">
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search keys..."
className="flex-1 min-w-[200px] px-4 py-2.5 bg-[#12141a] border border-[#1e2030] rounded-lg text-white text-sm placeholder-[#334155] focus:outline-none focus:border-[#3b82f6] transition-colors"
/>
<select
value={scopeFilter}
onChange={(e) => setScopeFilter(e.target.value as any)}
className="px-3 py-2.5 bg-[#12141a] border border-[#1e2030] rounded-lg text-white text-sm focus:outline-none focus:border-[#3b82f6]"
>
<option value="all">All scopes</option>
<option value="personal">Personal</option>
<option value="shared">Shared</option>
</select>
<button onClick={() => setModal({})} className="px-4 py-2.5 bg-[#3b82f6] hover:bg-[#2563eb] text-white text-sm font-semibold rounded-lg transition-colors whitespace-nowrap">
+ Add Key
</button>
</div>
{/* Stats */}
<div className="grid grid-cols-3 gap-4 mb-6">
{[
{ label: "Total Keys", value: entries.length },
{ label: "Shared", value: entries.filter(([, e]) => e.scope === "shared").length },
{ label: "Secrets", value: entries.filter(([, e]) => e.secret).length },
].map((s) => (
<div key={s.label} className="bg-[#12141a] border border-[#1e2030] rounded-xl px-5 py-4">
<div className="text-2xl font-bold text-white" style={{ fontFamily: "var(--font-heading)" }}>{s.value}</div>
<div className="text-xs text-[#64748b] mt-1">{s.label}</div>
</div>
))}
</div>
{/* Table */}
<div className="bg-[#12141a] border border-[#1e2030] rounded-xl p-5">
<ConfigTable
entries={filtered}
onEdit={(key, entry) => setModal({ key, entry })}
onDelete={handleDelete}
addToast={addToast}
/>
</div>
</>
) : (
<AdminPanel addToast={addToast} />
)}
</main>
{modal && (
<AddEditModal
editKey={modal.key}
editEntry={modal.entry}
onSave={handleSave}
onClose={() => setModal(null)}
/>
)}
</div>
);
}

View File

@ -0,0 +1,54 @@
import { useState } from "react";
export default function LoginPage({ onLogin }: { onLogin: () => void }) {
const [token, setToken] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await fetch("/config", { headers: { Authorization: `Bearer ${token.trim()}` } });
if (!res.ok) throw new Error("Invalid token");
localStorage.setItem("config-token", token.trim());
onLogin();
} catch {
setError("Authentication failed. Check your token.");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-[#0a0a0c]">
<form onSubmit={handleSubmit} className="w-full max-w-md p-8 bg-[#12141a] border border-[#1e2030] rounded-2xl">
<div className="mb-8 text-center">
<h1 className="text-3xl font-bold text-white mb-1" style={{ fontFamily: "var(--font-heading)" }}>
Config Service
</h1>
<p className="text-[#64748b] text-sm">Agent Configuration Management</p>
</div>
<label className="block text-sm text-[#64748b] mb-2 font-medium">API Token</label>
<input
type="password"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder="Enter your bearer token"
className="w-full px-4 py-3 bg-[#0a0a0c] border border-[#1e2030] rounded-lg text-white placeholder-[#334155] focus:outline-none focus:border-[#3b82f6] transition-colors"
style={{ fontFamily: "var(--font-mono)" }}
autoFocus
/>
{error && <p className="text-red-400 text-sm mt-2">{error}</p>}
<button
type="submit"
disabled={!token.trim() || loading}
className="w-full mt-6 py-3 bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-40 text-white font-semibold rounded-lg transition-colors"
>
{loading ? "Authenticating..." : "Connect"}
</button>
</form>
</div>
);
}

View File

@ -0,0 +1,31 @@
import { useEffect, useState } from "react";
import type { Toast as ToastType } from "../types";
export default function Toast({ toasts, remove }: { toasts: ToastType[]; remove: (id: number) => void }) {
return (
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2">
{toasts.map((t) => (
<ToastItem key={t.id} toast={t} remove={remove} />
))}
</div>
);
}
function ToastItem({ toast, remove }: { toast: ToastType; remove: (id: number) => void }) {
const [show, setShow] = useState(false);
useEffect(() => {
requestAnimationFrame(() => setShow(true));
const timer = setTimeout(() => { setShow(false); setTimeout(() => remove(toast.id), 300); }, 3000);
return () => clearTimeout(timer);
}, [toast.id, remove]);
return (
<div
className={`px-4 py-3 rounded-lg border text-sm font-medium transition-all duration-300 ${
show ? "opacity-100 translate-x-0" : "opacity-0 translate-x-4"
} ${toast.type === "error" ? "bg-red-500/10 border-red-500/30 text-red-400" : "bg-green-500/10 border-green-500/30 text-green-400"}`}
>
{toast.message}
</div>
);
}

View File

@ -0,0 +1,39 @@
import { useCallback } from "react";
const getToken = () => localStorage.getItem("config-token") || "";
export function useApi() {
const request = useCallback(async (path: string, options: RequestInit = {}) => {
const res = await fetch(path, {
...options,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getToken()}`,
...(options.headers || {}),
},
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || `${res.status} ${res.statusText}`);
}
if (res.status === 204) return null;
return res.json();
}, []);
const getConfig = () => request("/config");
const getKey = (key: string) => request(`/config/${encodeURIComponent(key)}`);
const putKey = (key: string, scope: string, body: { value: string; env?: boolean; secret?: boolean }) =>
request(`/config/${encodeURIComponent(key)}?scope=${scope}`, { method: "PUT", body: JSON.stringify(body) });
const patchKey = (key: string, scope: string, body: { env?: boolean; secret?: boolean }) =>
request(`/config/${encodeURIComponent(key)}?scope=${scope}`, { method: "PATCH", body: JSON.stringify(body) });
const deleteKey = (key: string, scope: string) =>
request(`/config/${encodeURIComponent(key)}?scope=${scope}`, { method: "DELETE" });
const getAgents = () => request("/admin/agents");
const getAgent = (id: string) => request(`/admin/agent/${encodeURIComponent(id)}`);
const createToken = (agent_id: string, role?: string) =>
request("/admin/token", { method: "POST", body: JSON.stringify({ agent_id, role }) });
const revokeToken = (id: string) =>
request(`/admin/token/${encodeURIComponent(id)}`, { method: "DELETE" });
return { getConfig, getKey, putKey, patchKey, deleteKey, getAgents, getAgent, createToken, revokeToken };
}

View File

@ -0,0 +1,31 @@
@import "tailwindcss";
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Plus+Jakarta+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');
@theme {
--color-bg: #0a0a0c;
--color-surface: #12141a;
--color-border: #1e2030;
--color-accent: #3b82f6;
--color-accent-hover: #2563eb;
--color-text: #e2e8f0;
--color-text-dim: #64748b;
--color-badge-shared: #3b82f6;
--color-badge-personal: #22c55e;
--color-badge-secret: #ef4444;
--color-badge-noenv: #eab308;
--font-heading: 'Space Grotesk', sans-serif;
--font-body: 'Plus Jakarta Sans', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
}
body {
background-color: var(--color-bg);
color: var(--color-text);
font-family: var(--font-body);
margin: 0;
}
* {
scrollbar-width: thin;
scrollbar-color: #1e2030 transparent;
}

View File

@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);

View File

@ -0,0 +1,25 @@
export interface ConfigEntry {
value: string;
scope: "personal" | "shared";
env: boolean;
secret: boolean;
updated_at: string;
}
export interface ConfigResponse {
agent_id: string;
role?: string;
secrets: Record<string, ConfigEntry>;
}
export interface Agent {
id: string;
role: string;
tokens?: { id: string; created_at: string }[];
}
export interface Toast {
id: number;
message: string;
type: "success" | "error";
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,12 @@
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { viteSingleFile } from "vite-plugin-singlefile";
export default defineConfig({
plugins: [react(), tailwindcss(), viteSingleFile()],
build: {
target: "esnext",
minify: "terser",
},
});

View File

@ -195,7 +195,62 @@ async function handleSync(auth: AuthInfo, kv: KVNamespace): Promise<Response> {
}
}
return json({ agent_id: auth.agent_id, secrets: resolved });
return json({ agent_id: auth.agent_id, role: auth.role, secrets: resolved });
}
// ── Public Profile endpoints ──────────────────────────────────────────
// GET /profiles — list all agents that have public profile entries
async function handleListProfiles(kv: KVNamespace): Promise<Response> {
const list = await kv.list({ prefix: "public:" });
const agentIds = new Set<string>();
for (const k of list.keys) {
// public:{agent_id}:{key}
const parts = k.name.split(":");
if (parts.length >= 3) agentIds.add(parts[1]);
}
return json({ agents: [...agentIds].sort() });
}
// GET /profile/:agent_id — list all public keys for an agent
async function handleGetProfile(agentId: string, kv: KVNamespace): Promise<Response> {
const list = await kv.list({ prefix: `public:${agentId}:` });
const profile: Record<string, { value: string; updated_at: string }> = {};
for (const k of list.keys) {
const key = k.name.replace(`public:${agentId}:`, "");
const entry = await kv.get<KVEntry>(k.name, "json");
if (entry) {
profile[key] = { value: entry.value, updated_at: entry.updated_at };
}
}
return json({ agent_id: agentId, profile });
}
// GET /profile/:agent_id/:key — read a single public key
async function handleGetProfileKey(agentId: string, key: string, kv: KVNamespace): Promise<Response> {
const entry = await kv.get<KVEntry>(`public:${agentId}:${key}`, "json");
if (!entry) return err("not found", 404);
return json({ agent_id: agentId, key, value: entry.value, updated_at: entry.updated_at });
}
// PUT /profile/:key — write to own public profile
async function handlePutProfileKey(key: string, auth: AuthInfo, kv: KVNamespace, request: Request): Promise<Response> {
const body = await request.json<{ value: string }>();
if (!body?.value && body?.value !== "") return err("missing 'value' in body");
const entry: KVEntry = {
value: body.value,
updated_at: new Date().toISOString(),
env: false,
secret: false,
};
await kv.put(`public:${auth.agent_id}:${key}`, JSON.stringify(entry));
return json({ agent_id: auth.agent_id, key, status: "ok" });
}
// DELETE /profile/:key — delete from own public profile
async function handleDeleteProfileKey(key: string, auth: AuthInfo, kv: KVNamespace): Promise<Response> {
await kv.delete(`public:${auth.agent_id}:${key}`);
return json({ agent_id: auth.agent_id, key, status: "deleted" });
}
// ── Admin endpoints ────────────────────────────────────────────────────
@ -232,9 +287,22 @@ async function handleAdminRevokeTokens(auth: AuthInfo, kv: KVNamespace, agentId:
async function handleAdminListAgents(auth: AuthInfo, kv: KVNamespace): Promise<Response> {
if (auth.role !== "admin") return err("admin required", 403);
const list = await kv.list({ prefix: "agent_tokens:" });
const agents = list.keys.map((k) => k.name.replace("agent_tokens:", ""));
return json({ agents });
// Collect agents from agent_tokens: prefix
const tokenList = await kv.list({ prefix: "agent_tokens:" });
const fromTokens = tokenList.keys.map((k) => k.name.replace("agent_tokens:", ""));
// Also collect agents from auth: entries
const authList = await kv.list({ prefix: "auth:" });
const agentIds = new Set<string>(fromTokens);
for (const key of authList.keys) {
const val = await kv.get(key.name);
if (val) {
try {
const parsed = JSON.parse(val);
if (parsed.agent_id) agentIds.add(parsed.agent_id);
} catch {}
}
}
return json({ agents: [...agentIds].sort() });
}
async function handleAdminInspect(auth: AuthInfo, kv: KVNamespace, agentId: string): Promise<Response> {
@ -292,6 +360,12 @@ export default {
// Health check
if (path === "/health") return json({ status: "ok" });
// Serve UI
if (path === "/" && method === "GET") {
const { renderUI } = await import("./ui.js");
return new Response(renderUI(), { headers: { "Content-Type": "text/html" } });
}
// Auth required for everything else
const auth = await authenticate(request, env.CONFIG_KV);
if (!auth) return err("unauthorized", 401);
@ -308,6 +382,36 @@ export default {
return handleList(url.searchParams.get("scope"), auth, env.CONFIG_KV);
}
// Public profile routes
if (path === "/profiles" && method === "GET") {
return handleListProfiles(env.CONFIG_KV);
}
// GET /profile/:agent_id or GET /profile/:agent_id/:key
if (path.startsWith("/profile/")) {
const profilePath = path.replace("/profile/", "");
const slashIdx = profilePath.indexOf("/");
if (slashIdx === -1) {
// /profile/:agent_id
const agentId = decodeURIComponent(profilePath);
if (method === "GET") return handleGetProfile(agentId, env.CONFIG_KV);
return err("method not allowed", 405);
}
const agentId = decodeURIComponent(profilePath.slice(0, slashIdx));
const key = decodeURIComponent(profilePath.slice(slashIdx + 1));
switch (method) {
case "GET":
return handleGetProfileKey(agentId, key, env.CONFIG_KV);
case "PUT":
if (agentId !== auth.agent_id) return err("can only write to own profile", 403);
return handlePutProfileKey(key, auth, env.CONFIG_KV, request);
case "DELETE":
if (agentId !== auth.agent_id) return err("can only delete from own profile", 403);
return handleDeleteProfileKey(key, auth, env.CONFIG_KV);
default:
return err("method not allowed", 405);
}
}
// Admin routes
if (path === "/admin/token" && method === "POST") {
return handleAdminCreateToken(auth, env.CONFIG_KV, request);

File diff suppressed because one or more lines are too long

28
scripts/build-ui.sh Executable file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
export PATH="$HOME/.bun/bin:$PATH"
echo "Building webui..."
cd packages/webui
bun run build
HTML=$(cat dist/index.html)
echo "Generating ui.ts..."
cat > ../worker/src/ui.ts << 'TSEOF'
export function renderUI(): string {
return UI_HTML;
}
TSEOF
# Use node to safely embed the HTML as a JS string
node -e "
const fs = require('fs');
const html = fs.readFileSync('dist/index.html', 'utf8');
const src = 'export function renderUI(): string {\n return ' + JSON.stringify(html) + ';\n}\n';
fs.writeFileSync('../worker/src/ui.ts', src);
"
echo "Done. Generated packages/worker/src/ui.ts"

View File

@ -1,43 +0,0 @@
#!/usr/bin/env python3
"""Register an agent token in the config service KV.
Usage: python3 register_agent.py <agent_id> <role> [token]
If token is omitted, a random one is generated.
Outputs the KV entry to add via wrangler CLI.
"""
import hashlib
import json
import secrets
import sys
def main():
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <agent_id> <role> [token]")
print(" role: agent or admin")
sys.exit(1)
agent_id = sys.argv[1]
role = sys.argv[2]
token = sys.argv[3] if len(sys.argv) > 3 else secrets.token_urlsafe(32)
if role not in ("agent", "admin"):
print("Role must be 'agent' or 'admin'", file=sys.stderr)
sys.exit(1)
token_hash = hashlib.sha256(token.encode()).hexdigest()
entry = json.dumps({"agent_id": agent_id, "role": role})
print(f"Agent ID: {agent_id}")
print(f"Role: {role}")
print(f"Token: {token}")
print(f"Token hash: {token_hash}")
print()
print("Add to KV:")
print(f' wrangler kv key put --binding CONFIG_KV "auth:{token_hash}" \'{entry}\'')
if __name__ == "__main__":
main()