Compare commits
5 Commits
feat/entry
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| a3b3c598ab | |||
| eadaa97caa | |||
| 58494b8fca | |||
| 117e334a07 | |||
| 211533346b |
5
.gitignore
vendored
5
.gitignore
vendored
@ -1 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.wrangler/
|
||||
.npmrc
|
||||
bun.lock
|
||||
package-lock.json
|
||||
|
||||
5
package.json
Normal file
5
package.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "config-service",
|
||||
"private": true,
|
||||
"workspaces": ["packages/*"]
|
||||
}
|
||||
1
packages/cfg/.gitignore
vendored
Normal file
1
packages/cfg/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
dist/
|
||||
17
packages/cfg/package.json
Normal file
17
packages/cfg/package.json
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "@shazhou/cfg",
|
||||
"version": "1.0.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
70
packages/cfg/src/api.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
91
packages/cfg/src/cli.ts
Normal file
91
packages/cfg/src/cli.ts
Normal file
@ -0,0 +1,91 @@
|
||||
import {
|
||||
cmdSync,
|
||||
cmdEnv,
|
||||
cmdGet,
|
||||
cmdSet,
|
||||
cmdUnset,
|
||||
cmdFlags,
|
||||
cmdList,
|
||||
cmdToken,
|
||||
cmdAdminAddUser,
|
||||
cmdAdminRemoveUser,
|
||||
cmdAdminListAgents,
|
||||
cmdAdminRefreshToken,
|
||||
cmdAdminInspect,
|
||||
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 "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);
|
||||
}
|
||||
374
cli/cfg.js → packages/cfg/src/commands.ts
Executable file → Normal file
374
cli/cfg.js → packages/cfg/src/commands.ts
Executable file → Normal file
@ -1,119 +1,17 @@
|
||||
#!/usr/bin/env node
|
||||
import {
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
loadCache,
|
||||
saveCache,
|
||||
ONE_DAY,
|
||||
TWO_HOURS,
|
||||
DEFAULT_ENDPOINT,
|
||||
type Cache,
|
||||
} from "./config.js";
|
||||
import { api, trySyncRemote } from "./api.js";
|
||||
|
||||
// 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;
|
||||
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();
|
||||
@ -125,7 +23,8 @@ function shouldAutoSync(cache) {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
async function cmdSync() {
|
||||
|
||||
export async function cmdSync(): Promise<void> {
|
||||
const { data } = await api("GET", "/config");
|
||||
if (!data?.secrets) {
|
||||
console.error("No secrets found");
|
||||
@ -136,13 +35,14 @@ async function cmdSync() {
|
||||
agent_id: data.agent_id,
|
||||
secrets: data.secrets,
|
||||
synced_at: now,
|
||||
attempted_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() {
|
||||
|
||||
export async function cmdEnv(): Promise<void> {
|
||||
let cache = loadCache();
|
||||
if (shouldAutoSync(cache)) {
|
||||
const ok = await trySyncRemote();
|
||||
@ -153,13 +53,16 @@ async function cmdEnv() {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
for (const [key, entry] of Object.entries(cache.secrets).sort(([a], [b]) => a.localeCompare(b))) {
|
||||
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) {
|
||||
|
||||
export async function cmdGet(key: string, remote: boolean): Promise<void> {
|
||||
if (remote) {
|
||||
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
|
||||
console.log(data.value);
|
||||
@ -168,8 +71,7 @@ async function cmdGet(key, remote) {
|
||||
let cache = loadCache();
|
||||
if (shouldAutoSync(cache)) {
|
||||
const ok = await trySyncRemote();
|
||||
if (ok)
|
||||
cache = loadCache();
|
||||
if (ok) cache = loadCache();
|
||||
else if (!cache) {
|
||||
console.error("No local cache and sync failed. Run: cfg sync");
|
||||
process.exit(1);
|
||||
@ -186,13 +88,18 @@ async function cmdGet(key, remote) {
|
||||
}
|
||||
console.log(entry.value);
|
||||
}
|
||||
async function cmdSet(args) {
|
||||
|
||||
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));
|
||||
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>");
|
||||
console.error(
|
||||
"Usage: cfg set [--shared] [--no-env] [--secret] <KEY> <VALUE>"
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const [key, ...rest] = filtered;
|
||||
@ -200,18 +107,25 @@ async function cmdSet(args) {
|
||||
const scope = shared ? "shared" : "personal";
|
||||
const body = { value, env: !noEnv, secret: isSecret };
|
||||
await api("PUT", `/config/${encodeURIComponent(key)}?scope=${scope}`, body);
|
||||
const flags = [];
|
||||
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() };
|
||||
cache.secrets[key] = {
|
||||
value,
|
||||
scope,
|
||||
env: !noEnv,
|
||||
secret: isSecret,
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
saveCache(cache);
|
||||
}
|
||||
}
|
||||
async function cmdUnset(args) {
|
||||
|
||||
export async function cmdUnset(args: string[]): Promise<void> {
|
||||
const shared = args.includes("--shared");
|
||||
const filtered = args.filter((a) => a !== "--shared");
|
||||
if (filtered.length < 1) {
|
||||
@ -228,12 +142,12 @@ async function cmdUnset(args) {
|
||||
saveCache(cache);
|
||||
}
|
||||
}
|
||||
async function cmdList() {
|
||||
|
||||
export async function cmdList(): Promise<void> {
|
||||
let cache = loadCache();
|
||||
if (shouldAutoSync(cache)) {
|
||||
const ok = await trySyncRemote();
|
||||
if (ok)
|
||||
cache = loadCache();
|
||||
if (ok) cache = loadCache();
|
||||
else if (!cache) {
|
||||
console.error("No local cache and sync failed. Run: cfg sync");
|
||||
process.exit(1);
|
||||
@ -251,43 +165,95 @@ async function cmdList() {
|
||||
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 = [];
|
||||
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(`
|
||||
Total: ${keys.length} keys (agent: ${cache.agent_id})`);
|
||||
console.log(`\nTotal: ${keys.length} keys (agent: ${cache.agent_id})`);
|
||||
console.log(`Last sync: ${cache.synced_at}`);
|
||||
}
|
||||
function cmdToken(token) {
|
||||
|
||||
export function cmdToken(token: string): void {
|
||||
const cfg = loadConfig();
|
||||
cfg.token = token;
|
||||
saveConfig(cfg);
|
||||
console.log("✓ Token saved");
|
||||
}
|
||||
async function cmdAdminAddUser(args) {
|
||||
|
||||
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 });
|
||||
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) {
|
||||
|
||||
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])}`);
|
||||
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() {
|
||||
|
||||
export async function cmdAdminListAgents(): Promise<void> {
|
||||
const { data } = await api("GET", "/admin/agents");
|
||||
if (!data.agents?.length) {
|
||||
console.log("No agents found");
|
||||
@ -298,7 +264,8 @@ async function cmdAdminListAgents() {
|
||||
console.log(` ${agent}`);
|
||||
}
|
||||
}
|
||||
async function cmdAdminRefreshToken(args) {
|
||||
|
||||
export async function cmdAdminRefreshToken(args: string[]): Promise<void> {
|
||||
if (!args[0]) {
|
||||
console.error("Usage: cfg admin refresh <AGENT_ID>");
|
||||
process.exit(1);
|
||||
@ -309,12 +276,16 @@ async function cmdAdminRefreshToken(args) {
|
||||
console.log(`✓ Refreshed token for ${data.agent_id}`);
|
||||
console.log(` Token: ${data.token}`);
|
||||
}
|
||||
async function cmdAdminInspect(args) {
|
||||
|
||||
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])}`);
|
||||
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;
|
||||
@ -323,44 +294,16 @@ async function cmdAdminInspect(args) {
|
||||
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 ";
|
||||
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})`);
|
||||
console.log(`\nTotal: ${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() {
|
||||
|
||||
export function showHelp(): void {
|
||||
console.log(`cfg — config.shazhou.work CLI
|
||||
|
||||
Usage:
|
||||
@ -399,76 +342,3 @@ Environment:
|
||||
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);
|
||||
}
|
||||
73
packages/cfg/src/config.ts
Normal file
73
packages/cfg/src/config.ts
Normal 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;
|
||||
}
|
||||
12
packages/cfg/tsconfig.json
Normal file
12
packages/cfg/tsconfig.json
Normal 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
24
packages/webui/.gitignore
vendored
Normal 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
73
packages/webui/README.md
Normal 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...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
packages/webui/eslint.config.js
Normal file
23
packages/webui/eslint.config.js
Normal 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
12
packages/webui/index.html
Normal 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>
|
||||
35
packages/webui/package.json
Normal file
35
packages/webui/package.json
Normal 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"
|
||||
}
|
||||
}
|
||||
34
packages/webui/src/App.tsx
Normal file
34
packages/webui/src/App.tsx
Normal 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)} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
90
packages/webui/src/components/AddEditModal.tsx
Normal file
90
packages/webui/src/components/AddEditModal.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
114
packages/webui/src/components/AdminPanel.tsx
Normal file
114
packages/webui/src/components/AdminPanel.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
119
packages/webui/src/components/ConfigTable.tsx
Normal file
119
packages/webui/src/components/ConfigTable.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
200
packages/webui/src/components/Dashboard.tsx
Normal file
200
packages/webui/src/components/Dashboard.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
54
packages/webui/src/components/LoginPage.tsx
Normal file
54
packages/webui/src/components/LoginPage.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
31
packages/webui/src/components/Toast.tsx
Normal file
31
packages/webui/src/components/Toast.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
39
packages/webui/src/hooks/useApi.ts
Normal file
39
packages/webui/src/hooks/useApi.ts
Normal 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 };
|
||||
}
|
||||
31
packages/webui/src/index.css
Normal file
31
packages/webui/src/index.css
Normal 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;
|
||||
}
|
||||
10
packages/webui/src/main.tsx
Normal file
10
packages/webui/src/main.tsx
Normal 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>
|
||||
);
|
||||
25
packages/webui/src/types.ts
Normal file
25
packages/webui/src/types.ts
Normal 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";
|
||||
}
|
||||
25
packages/webui/tsconfig.app.json
Normal file
25
packages/webui/tsconfig.app.json
Normal 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"]
|
||||
}
|
||||
7
packages/webui/tsconfig.json
Normal file
7
packages/webui/tsconfig.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
24
packages/webui/tsconfig.node.json
Normal file
24
packages/webui/tsconfig.node.json
Normal 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"]
|
||||
}
|
||||
12
packages/webui/vite.config.ts
Normal file
12
packages/webui/vite.config.ts
Normal 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",
|
||||
},
|
||||
});
|
||||
@ -195,7 +195,7 @@ 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 });
|
||||
}
|
||||
|
||||
// ── Admin endpoints ────────────────────────────────────────────────────
|
||||
@ -232,9 +232,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 +305,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);
|
||||
3
packages/worker/src/ui.ts
Normal file
3
packages/worker/src/ui.ts
Normal file
File diff suppressed because one or more lines are too long
28
scripts/build-ui.sh
Executable file
28
scripts/build-ui.sh
Executable 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"
|
||||
@ -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()
|
||||
Loading…
x
Reference in New Issue
Block a user