Compare commits
No commits in common. "main" and "feat/entry-flags" have entirely different histories.
main
...
feat/entry
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,6 +1 @@
|
|||||||
node_modules/
|
|
||||||
dist/
|
|
||||||
.wrangler/
|
.wrangler/
|
||||||
.npmrc
|
|
||||||
bun.lock
|
|
||||||
package-lock.json
|
|
||||||
|
|||||||
374
packages/cfg/src/commands.ts → cli/cfg.js
Normal file → Executable file
374
packages/cfg/src/commands.ts → cli/cfg.js
Normal file → Executable file
@ -1,17 +1,119 @@
|
|||||||
import {
|
#!/usr/bin/env node
|
||||||
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 {
|
// src/cli.ts
|
||||||
if (!cache) return true;
|
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 now = Date.now();
|
||||||
const syncedAt = new Date(cache.synced_at).getTime();
|
const syncedAt = new Date(cache.synced_at).getTime();
|
||||||
const attemptedAt = new Date(cache.attempted_at || cache.synced_at).getTime();
|
const attemptedAt = new Date(cache.attempted_at || cache.synced_at).getTime();
|
||||||
@ -23,8 +125,7 @@ export function shouldAutoSync(cache: Cache | null): boolean {
|
|||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
async function cmdSync() {
|
||||||
export async function cmdSync(): Promise<void> {
|
|
||||||
const { data } = await api("GET", "/config");
|
const { data } = await api("GET", "/config");
|
||||||
if (!data?.secrets) {
|
if (!data?.secrets) {
|
||||||
console.error("No secrets found");
|
console.error("No secrets found");
|
||||||
@ -35,14 +136,13 @@ export async function cmdSync(): Promise<void> {
|
|||||||
agent_id: data.agent_id,
|
agent_id: data.agent_id,
|
||||||
secrets: data.secrets,
|
secrets: data.secrets,
|
||||||
synced_at: now,
|
synced_at: now,
|
||||||
attempted_at: now,
|
attempted_at: now
|
||||||
};
|
};
|
||||||
saveCache(cache);
|
saveCache(cache);
|
||||||
const count = Object.keys(cache.secrets).length;
|
const count = Object.keys(cache.secrets).length;
|
||||||
console.log(`✓ Synced ${count} keys (agent: ${cache.agent_id})`);
|
console.log(`✓ Synced ${count} keys (agent: ${cache.agent_id})`);
|
||||||
}
|
}
|
||||||
|
async function cmdEnv() {
|
||||||
export async function cmdEnv(): Promise<void> {
|
|
||||||
let cache = loadCache();
|
let cache = loadCache();
|
||||||
if (shouldAutoSync(cache)) {
|
if (shouldAutoSync(cache)) {
|
||||||
const ok = await trySyncRemote();
|
const ok = await trySyncRemote();
|
||||||
@ -53,16 +153,13 @@ export async function cmdEnv(): Promise<void> {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const [key, entry] of Object.entries(cache!.secrets).sort(([a], [b]) =>
|
for (const [key, entry] of Object.entries(cache.secrets).sort(([a], [b]) => a.localeCompare(b))) {
|
||||||
a.localeCompare(b)
|
|
||||||
)) {
|
|
||||||
if (entry.env === false) continue;
|
if (entry.env === false) continue;
|
||||||
const escaped = entry.value.replace(/'/g, "'\\''");
|
const escaped = entry.value.replace(/'/g, "'\\''");
|
||||||
console.log(`export ${key}='${escaped}'`);
|
console.log(`export ${key}='${escaped}'`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function cmdGet(key, remote) {
|
||||||
export async function cmdGet(key: string, remote: boolean): Promise<void> {
|
|
||||||
if (remote) {
|
if (remote) {
|
||||||
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
|
const { data } = await api("GET", `/config/${encodeURIComponent(key)}`);
|
||||||
console.log(data.value);
|
console.log(data.value);
|
||||||
@ -71,7 +168,8 @@ export async function cmdGet(key: string, remote: boolean): Promise<void> {
|
|||||||
let cache = loadCache();
|
let cache = loadCache();
|
||||||
if (shouldAutoSync(cache)) {
|
if (shouldAutoSync(cache)) {
|
||||||
const ok = await trySyncRemote();
|
const ok = await trySyncRemote();
|
||||||
if (ok) cache = loadCache();
|
if (ok)
|
||||||
|
cache = loadCache();
|
||||||
else if (!cache) {
|
else if (!cache) {
|
||||||
console.error("No local cache and sync failed. Run: cfg sync");
|
console.error("No local cache and sync failed. Run: cfg sync");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@ -88,18 +186,13 @@ export async function cmdGet(key: string, remote: boolean): Promise<void> {
|
|||||||
}
|
}
|
||||||
console.log(entry.value);
|
console.log(entry.value);
|
||||||
}
|
}
|
||||||
|
async function cmdSet(args) {
|
||||||
export async function cmdSet(args: string[]): Promise<void> {
|
|
||||||
const shared = args.includes("--shared");
|
const shared = args.includes("--shared");
|
||||||
const noEnv = args.includes("--no-env");
|
const noEnv = args.includes("--no-env");
|
||||||
const isSecret = args.includes("--secret");
|
const isSecret = args.includes("--secret");
|
||||||
const filtered = args.filter(
|
const filtered = args.filter((a) => !["--shared", "--no-env", "--secret"].includes(a));
|
||||||
(a) => !["--shared", "--no-env", "--secret"].includes(a)
|
|
||||||
);
|
|
||||||
if (filtered.length < 2) {
|
if (filtered.length < 2) {
|
||||||
console.error(
|
console.error("Usage: cfg set [--shared] [--no-env] [--secret] <KEY> <VALUE>");
|
||||||
"Usage: cfg set [--shared] [--no-env] [--secret] <KEY> <VALUE>"
|
|
||||||
);
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const [key, ...rest] = filtered;
|
const [key, ...rest] = filtered;
|
||||||
@ -107,25 +200,18 @@ export async function cmdSet(args: string[]): Promise<void> {
|
|||||||
const scope = shared ? "shared" : "personal";
|
const scope = shared ? "shared" : "personal";
|
||||||
const body = { value, env: !noEnv, secret: isSecret };
|
const body = { value, env: !noEnv, secret: isSecret };
|
||||||
await api("PUT", `/config/${encodeURIComponent(key)}?scope=${scope}`, body);
|
await api("PUT", `/config/${encodeURIComponent(key)}?scope=${scope}`, body);
|
||||||
const flags: string[] = [];
|
const flags = [];
|
||||||
if (noEnv) flags.push("no-env");
|
if (noEnv) flags.push("no-env");
|
||||||
if (isSecret) flags.push("secret");
|
if (isSecret) flags.push("secret");
|
||||||
const flagStr = flags.length ? ` [${flags.join(", ")}]` : "";
|
const flagStr = flags.length ? ` [${flags.join(", ")}]` : "";
|
||||||
console.log(`✓ ${key} (${scope})${flagStr}`);
|
console.log(`✓ ${key} (${scope})${flagStr}`);
|
||||||
const cache = loadCache();
|
const cache = loadCache();
|
||||||
if (cache) {
|
if (cache) {
|
||||||
cache.secrets[key] = {
|
cache.secrets[key] = { value, scope, env: !noEnv, secret: isSecret, updated_at: new Date().toISOString() };
|
||||||
value,
|
|
||||||
scope,
|
|
||||||
env: !noEnv,
|
|
||||||
secret: isSecret,
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
saveCache(cache);
|
saveCache(cache);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function cmdUnset(args) {
|
||||||
export async function cmdUnset(args: string[]): Promise<void> {
|
|
||||||
const shared = args.includes("--shared");
|
const shared = args.includes("--shared");
|
||||||
const filtered = args.filter((a) => a !== "--shared");
|
const filtered = args.filter((a) => a !== "--shared");
|
||||||
if (filtered.length < 1) {
|
if (filtered.length < 1) {
|
||||||
@ -142,12 +228,12 @@ export async function cmdUnset(args: string[]): Promise<void> {
|
|||||||
saveCache(cache);
|
saveCache(cache);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function cmdList() {
|
||||||
export async function cmdList(): Promise<void> {
|
|
||||||
let cache = loadCache();
|
let cache = loadCache();
|
||||||
if (shouldAutoSync(cache)) {
|
if (shouldAutoSync(cache)) {
|
||||||
const ok = await trySyncRemote();
|
const ok = await trySyncRemote();
|
||||||
if (ok) cache = loadCache();
|
if (ok)
|
||||||
|
cache = loadCache();
|
||||||
else if (!cache) {
|
else if (!cache) {
|
||||||
console.error("No local cache and sync failed. Run: cfg sync");
|
console.error("No local cache and sync failed. Run: cfg sync");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@ -165,95 +251,43 @@ export async function cmdList(): Promise<void> {
|
|||||||
const maxLen = Math.max(...keys.map((k) => k.length));
|
const maxLen = Math.max(...keys.map((k) => k.length));
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
const entry = cache.secrets[key];
|
const entry = cache.secrets[key];
|
||||||
const scope =
|
const scope = entry.scope === "personal" ? "\x1B[32mpersonal\x1B[0m" : "\x1B[34mshared\x1B[0m ";
|
||||||
entry.scope === "personal"
|
const flags = [];
|
||||||
? "\x1B[32mpersonal\x1B[0m"
|
|
||||||
: "\x1B[34mshared\x1B[0m ";
|
|
||||||
const flags: string[] = [];
|
|
||||||
if (entry.env === false) flags.push("\x1B[33mno-env\x1B[0m");
|
if (entry.env === false) flags.push("\x1B[33mno-env\x1B[0m");
|
||||||
if (entry.secret) flags.push("\x1B[31msecret\x1B[0m");
|
if (entry.secret) flags.push("\x1B[31msecret\x1B[0m");
|
||||||
const flagStr = flags.length ? " " + flags.join(" ") : "";
|
const flagStr = flags.length ? " " + flags.join(" ") : "";
|
||||||
console.log(` ${key.padEnd(maxLen + 2)}${scope}${flagStr}`);
|
console.log(` ${key.padEnd(maxLen + 2)}${scope}${flagStr}`);
|
||||||
}
|
}
|
||||||
console.log(`\nTotal: ${keys.length} keys (agent: ${cache.agent_id})`);
|
console.log(`
|
||||||
|
Total: ${keys.length} keys (agent: ${cache.agent_id})`);
|
||||||
console.log(`Last sync: ${cache.synced_at}`);
|
console.log(`Last sync: ${cache.synced_at}`);
|
||||||
}
|
}
|
||||||
|
function cmdToken(token) {
|
||||||
export function cmdToken(token: string): void {
|
|
||||||
const cfg = loadConfig();
|
const cfg = loadConfig();
|
||||||
cfg.token = token;
|
cfg.token = token;
|
||||||
saveConfig(cfg);
|
saveConfig(cfg);
|
||||||
console.log("✓ Token saved");
|
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 role = args.includes("--admin") ? "admin" : "agent";
|
||||||
const filtered = args.filter((a) => a !== "--admin");
|
const filtered = args.filter((a) => a !== "--admin");
|
||||||
if (!filtered[0]) {
|
if (!filtered[0]) {
|
||||||
console.error("Usage: cfg admin add <AGENT_ID> [--admin]");
|
console.error("Usage: cfg admin add <AGENT_ID> [--admin]");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const { data } = await api("POST", "/admin/token", {
|
const { data } = await api("POST", "/admin/token", { agent_id: filtered[0], role });
|
||||||
agent_id: filtered[0],
|
|
||||||
role,
|
|
||||||
});
|
|
||||||
console.log(`✓ Created ${data.role} token for ${data.agent_id}`);
|
console.log(`✓ Created ${data.role} token for ${data.agent_id}`);
|
||||||
console.log(` Token: ${data.token}`);
|
console.log(` Token: ${data.token}`);
|
||||||
}
|
}
|
||||||
|
async function cmdAdminRemoveUser(args) {
|
||||||
export async function cmdAdminRemoveUser(args: string[]): Promise<void> {
|
|
||||||
if (!args[0]) {
|
if (!args[0]) {
|
||||||
console.error("Usage: cfg admin remove <AGENT_ID>");
|
console.error("Usage: cfg admin remove <AGENT_ID>");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const { data } = await api(
|
const { data } = await api("DELETE", `/admin/token/${encodeURIComponent(args[0])}`);
|
||||||
"DELETE",
|
|
||||||
`/admin/token/${encodeURIComponent(args[0])}`
|
|
||||||
);
|
|
||||||
console.log(`✓ Revoked ${data.tokens_revoked} token(s) for ${data.agent_id}`);
|
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");
|
const { data } = await api("GET", "/admin/agents");
|
||||||
if (!data.agents?.length) {
|
if (!data.agents?.length) {
|
||||||
console.log("No agents found");
|
console.log("No agents found");
|
||||||
@ -264,8 +298,7 @@ export async function cmdAdminListAgents(): Promise<void> {
|
|||||||
console.log(` ${agent}`);
|
console.log(` ${agent}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function cmdAdminRefreshToken(args) {
|
||||||
export async function cmdAdminRefreshToken(args: string[]): Promise<void> {
|
|
||||||
if (!args[0]) {
|
if (!args[0]) {
|
||||||
console.error("Usage: cfg admin refresh <AGENT_ID>");
|
console.error("Usage: cfg admin refresh <AGENT_ID>");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@ -276,16 +309,12 @@ export async function cmdAdminRefreshToken(args: string[]): Promise<void> {
|
|||||||
console.log(`✓ Refreshed token for ${data.agent_id}`);
|
console.log(`✓ Refreshed token for ${data.agent_id}`);
|
||||||
console.log(` Token: ${data.token}`);
|
console.log(` Token: ${data.token}`);
|
||||||
}
|
}
|
||||||
|
async function cmdAdminInspect(args) {
|
||||||
export async function cmdAdminInspect(args: string[]): Promise<void> {
|
|
||||||
if (!args[0]) {
|
if (!args[0]) {
|
||||||
console.error("Usage: cfg admin inspect <AGENT_ID>");
|
console.error("Usage: cfg admin inspect <AGENT_ID>");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const { data } = await api(
|
const { data } = await api("GET", `/admin/agent/${encodeURIComponent(args[0])}`);
|
||||||
"GET",
|
|
||||||
`/admin/agent/${encodeURIComponent(args[0])}`
|
|
||||||
);
|
|
||||||
if (!data.secrets || Object.keys(data.secrets).length === 0) {
|
if (!data.secrets || Object.keys(data.secrets).length === 0) {
|
||||||
console.log(`No keys for ${data.agent_id}`);
|
console.log(`No keys for ${data.agent_id}`);
|
||||||
return;
|
return;
|
||||||
@ -294,16 +323,44 @@ export async function cmdAdminInspect(args: string[]): Promise<void> {
|
|||||||
const maxLen = Math.max(...keys.map((k) => k.length));
|
const maxLen = Math.max(...keys.map((k) => k.length));
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
const entry = data.secrets[key];
|
const entry = data.secrets[key];
|
||||||
const scope =
|
const scope = entry.scope === "personal" ? "\x1B[32mpersonal\x1B[0m" : "\x1B[34mshared\x1B[0m ";
|
||||||
entry.scope === "personal"
|
|
||||||
? "\x1B[32mpersonal\x1B[0m"
|
|
||||||
: "\x1B[34mshared\x1B[0m ";
|
|
||||||
console.log(` ${key.padEnd(maxLen + 2)}${scope}`);
|
console.log(` ${key.padEnd(maxLen + 2)}${scope}`);
|
||||||
}
|
}
|
||||||
console.log(`\nTotal: ${keys.length} keys (agent: ${data.agent_id})`);
|
console.log(`
|
||||||
|
Total: ${keys.length} keys (agent: ${data.agent_id})`);
|
||||||
}
|
}
|
||||||
|
async function cmdFlags(args) {
|
||||||
export function showHelp(): 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 = {};
|
||||||
|
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
|
console.log(`cfg — config.shazhou.work CLI
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
@ -342,3 +399,76 @@ Environment:
|
|||||||
Shell setup:
|
Shell setup:
|
||||||
eval $(cfg env) Add to .profile / .bashrc / .zshrc`);
|
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);
|
||||||
|
}
|
||||||
@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "config-service",
|
|
||||||
"private": true,
|
|
||||||
"workspaces": ["packages/*"]
|
|
||||||
}
|
|
||||||
1
packages/cfg/.gitignore
vendored
1
packages/cfg/.gitignore
vendored
@ -1 +0,0 @@
|
|||||||
dist/
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
@ -1,70 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,91 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@ -1,73 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2022",
|
|
||||||
"module": "ES2022",
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"strict": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"outDir": "dist",
|
|
||||||
"rootDir": "src"
|
|
||||||
},
|
|
||||||
"include": ["src"]
|
|
||||||
}
|
|
||||||
24
packages/webui/.gitignore
vendored
24
packages/webui/.gitignore
vendored
@ -1,24 +0,0 @@
|
|||||||
# 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?
|
|
||||||
@ -1,73 +0,0 @@
|
|||||||
# 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...
|
|
||||||
},
|
|
||||||
},
|
|
||||||
])
|
|
||||||
```
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
])
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
<!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>
|
|
||||||
@ -1,35 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,34 +0,0 @@
|
|||||||
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)} />
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,90 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,114 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,119 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,200 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,54 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,39 +0,0 @@
|
|||||||
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 };
|
|
||||||
}
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
@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;
|
|
||||||
}
|
|
||||||
@ -1,10 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
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";
|
|
||||||
}
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
{
|
|
||||||
"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"]
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"files": [],
|
|
||||||
"references": [
|
|
||||||
{ "path": "./tsconfig.app.json" },
|
|
||||||
{ "path": "./tsconfig.node.json" }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
{
|
|
||||||
"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"]
|
|
||||||
}
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
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",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
File diff suppressed because one or more lines are too long
@ -1,28 +0,0 @@
|
|||||||
#!/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"
|
|
||||||
43
scripts/register_agent.py
Normal file
43
scripts/register_agent.py
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
#!/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()
|
||||||
@ -195,7 +195,7 @@ async function handleSync(auth: AuthInfo, kv: KVNamespace): Promise<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return json({ agent_id: auth.agent_id, role: auth.role, secrets: resolved });
|
return json({ agent_id: auth.agent_id, secrets: resolved });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Admin endpoints ────────────────────────────────────────────────────
|
// ── Admin endpoints ────────────────────────────────────────────────────
|
||||||
@ -232,22 +232,9 @@ async function handleAdminRevokeTokens(auth: AuthInfo, kv: KVNamespace, agentId:
|
|||||||
|
|
||||||
async function handleAdminListAgents(auth: AuthInfo, kv: KVNamespace): Promise<Response> {
|
async function handleAdminListAgents(auth: AuthInfo, kv: KVNamespace): Promise<Response> {
|
||||||
if (auth.role !== "admin") return err("admin required", 403);
|
if (auth.role !== "admin") return err("admin required", 403);
|
||||||
// Collect agents from agent_tokens: prefix
|
const list = await kv.list({ prefix: "agent_tokens:" });
|
||||||
const tokenList = await kv.list({ prefix: "agent_tokens:" });
|
const agents = list.keys.map((k) => k.name.replace("agent_tokens:", ""));
|
||||||
const fromTokens = tokenList.keys.map((k) => k.name.replace("agent_tokens:", ""));
|
return json({ agents });
|
||||||
// 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> {
|
async function handleAdminInspect(auth: AuthInfo, kv: KVNamespace, agentId: string): Promise<Response> {
|
||||||
@ -305,12 +292,6 @@ export default {
|
|||||||
// Health check
|
// Health check
|
||||||
if (path === "/health") return json({ status: "ok" });
|
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
|
// Auth required for everything else
|
||||||
const auth = await authenticate(request, env.CONFIG_KV);
|
const auth = await authenticate(request, env.CONFIG_KV);
|
||||||
if (!auth) return err("unauthorized", 401);
|
if (!auth) return err("unauthorized", 401);
|
||||||
Loading…
x
Reference in New Issue
Block a user