@simonfestl/husky-cli 1.9.2 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -143,6 +143,76 @@ husky e2e list --task <id> # List artifacts
143
143
  husky e2e clean --older-than 7 # Clean old artifacts
144
144
  ```
145
145
 
146
+ ### PR Management (PR Agent)
147
+
148
+ ```bash
149
+ husky pr list # List open PRs
150
+ husky pr get <pr-number> # Get PR details
151
+ husky pr review <pr-number> # Start review
152
+ husky pr approve <pr-number> # Approve PR
153
+ husky pr request-changes <pr-number> --comment "..."
154
+ husky pr merge <pr-number> # Merge PR
155
+ husky pr close <pr-number> # Close PR
156
+ ```
157
+
158
+ ### Infrastructure (DevOps)
159
+
160
+ ```bash
161
+ husky infra status # Overall infra status
162
+ husky infra vms # List all VMs
163
+ husky infra services # Cloud Run services
164
+ husky infra logs <service> # Service logs
165
+ husky infra metrics # Resource metrics
166
+ ```
167
+
168
+ ### YouTube Summarization
169
+
170
+ ```bash
171
+ husky youtube <url> # Summarize video with Gemini AI
172
+ husky youtube <url> --remember # Also store in Second Brain
173
+ husky youtube <url> --json # JSON output
174
+ ```
175
+
176
+ ### Image Generation
177
+
178
+ ```bash
179
+ husky image "a futuristic city" # Generate image with Imagen 3
180
+ husky image "..." --output ./image.png # Save to file
181
+ husky image "..." --aspect 16:9 # Aspect ratio
182
+ ```
183
+
184
+ ### Mermaid Diagrams
185
+
186
+ ```bash
187
+ husky mermaid validate <file> # Validate Mermaid syntax
188
+ husky mermaid validate --stdin # Validate from stdin
189
+ ```
190
+
191
+ ### Service Accounts
192
+
193
+ ```bash
194
+ husky sa list # List service accounts
195
+ husky sa create <name> --role worker # Create service account
196
+ husky sa get <id> # Get details
197
+ husky sa delete <id> # Delete service account
198
+ ```
199
+
200
+ ### Agent Messaging
201
+
202
+ ```bash
203
+ husky agent-msg send <to> "message" # Send to another agent
204
+ husky agent-msg inbox # Check inbox
205
+ husky agent-msg read <id> # Read message
206
+ ```
207
+
208
+ ### Preview Deployments
209
+
210
+ ```bash
211
+ husky preview list # List PR previews
212
+ husky preview get <pr-number> # Get preview URL
213
+ husky preview logs <pr-number> # Preview logs
214
+ ```
215
+
146
216
  ### Business Strategy
147
217
 
148
218
  ```bash
@@ -249,6 +319,41 @@ husky config list
249
319
  husky config test
250
320
  ```
251
321
 
322
+ ### Authentication (Session Tokens)
323
+
324
+ Session tokens provide short-lived JWT authentication for agents. They are created using `HUSKY_API_KEY` and auto-refresh when expired.
325
+
326
+ ```bash
327
+ # Login (creates 1-hour session token)
328
+ husky auth login --agent supervisor
329
+ husky auth login --agent husky-worker-1
330
+
331
+ # Check session status
332
+ husky auth session
333
+ husky auth session --json
334
+
335
+ # Refresh token manually
336
+ husky auth refresh
337
+ husky auth refresh --agent supervisor
338
+
339
+ # Logout (clear session)
340
+ husky auth logout
341
+ ```
342
+
343
+ **VM Startup Pattern:**
344
+ ```bash
345
+ #!/bin/bash
346
+ VM_NAME=$(hostname)
347
+ husky auth login --agent "$VM_NAME"
348
+ # All subsequent commands use Bearer token
349
+ ```
350
+
351
+ **How it works:**
352
+ 1. `HUSKY_API_KEY` is used once to create a session token
353
+ 2. All subsequent API calls use `Authorization: Bearer <token>`
354
+ 3. Token auto-refreshes when expired or within 5 minutes of expiry
355
+ 4. Falls back to `x-api-key` if refresh fails
356
+
252
357
  ### Help & Documentation
253
358
 
254
359
  ```bash
@@ -328,6 +433,27 @@ husky --version
328
433
 
329
434
  ## Changelog
330
435
 
436
+ ### v1.12.0 (2026-01-12) - Session Token Authentication
437
+
438
+ **New Features:**
439
+ - `husky auth login --agent <name>` - Create session token from HUSKY_API_KEY
440
+ - `husky auth logout` - Clear session token
441
+ - `husky auth session` - Show session status (agent, role, expiry)
442
+ - `husky auth refresh` - Manually refresh token
443
+
444
+ **Improvements:**
445
+ - All API calls now use Bearer token authentication (auto-refresh)
446
+ - Token auto-refreshes when expired or within 5 minutes of expiry
447
+ - Falls back to x-api-key for backwards compatibility
448
+ - JWT_SECRET now required in production (fail-fast)
449
+
450
+ **Documentation:**
451
+ - Added missing command sections: pr, infra, youtube, image, mermaid, sa, agent-msg, preview
452
+ - Updated architecture docs with session token flow
453
+
454
+ **Code Quality:**
455
+ - Removed `as any` type suppression in sop.ts
456
+
331
457
  ### v1.7.0 (2026-01-11) - E2E Agent Production Ready
332
458
 
333
459
  **New Features:**
@@ -0,0 +1,2 @@
1
+ import { Command } from "commander";
2
+ export declare const authCommand: Command;
@@ -0,0 +1,437 @@
1
+ import { Command } from "commander";
2
+ import { getConfig, setSessionConfig, clearSessionConfig, getSessionConfig } from "./config.js";
3
+ import { getPermissions, clearPermissionsCache, getCacheStatus, hasPermission, canAccessKnowledgeBase } from "../lib/permissions-cache.js";
4
+ const API_KEY_ROLES = [
5
+ "admin", "supervisor", "worker", "reviewer", "support",
6
+ "purchasing", "ops", "e2e_agent", "pr_agent"
7
+ ];
8
+ async function apiRequest(path, options = {}) {
9
+ const config = getConfig();
10
+ if (!config.apiUrl || !config.apiKey) {
11
+ throw new Error("API not configured. Run: husky config set api-url <url> && husky config set api-key <key>");
12
+ }
13
+ const url = new URL(path, config.apiUrl);
14
+ const res = await fetch(url.toString(), {
15
+ method: options.method || "GET",
16
+ headers: {
17
+ "x-api-key": config.apiKey,
18
+ "Content-Type": "application/json",
19
+ },
20
+ body: options.body ? JSON.stringify(options.body) : undefined,
21
+ });
22
+ if (!res.ok) {
23
+ const error = await res.json().catch(() => ({ error: res.statusText }));
24
+ throw new Error(error.message || error.error || `HTTP ${res.status}`);
25
+ }
26
+ return res.json();
27
+ }
28
+ export const authCommand = new Command("auth")
29
+ .description("Manage API keys and authentication");
30
+ authCommand
31
+ .command("keys")
32
+ .description("List all API keys")
33
+ .option("--include-revoked", "Include revoked keys")
34
+ .option("--json", "Output as JSON")
35
+ .action(async (options) => {
36
+ try {
37
+ const query = options.includeRevoked ? "?includeRevoked=true" : "";
38
+ const data = await apiRequest(`/api/auth/keys${query}`);
39
+ if (options.json) {
40
+ console.log(JSON.stringify(data.keys, null, 2));
41
+ return;
42
+ }
43
+ if (data.keys.length === 0) {
44
+ console.log("No API keys found.");
45
+ return;
46
+ }
47
+ console.log("\nAPI Keys:");
48
+ console.log("─".repeat(80));
49
+ for (const key of data.keys) {
50
+ const status = key.revoked ? "🔴 REVOKED" : "🟢 ACTIVE";
51
+ const expires = key.expiresAt ? new Date(key.expiresAt).toLocaleDateString() : "Never";
52
+ const lastUsed = key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never";
53
+ console.log(`${status} ${key.keyPrefix}... ${key.name}`);
54
+ console.log(` Role: ${key.role} | Expires: ${expires} | Last used: ${lastUsed}`);
55
+ console.log(` ID: ${key.id}`);
56
+ console.log("");
57
+ }
58
+ }
59
+ catch (error) {
60
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
61
+ process.exit(1);
62
+ }
63
+ });
64
+ authCommand
65
+ .command("create-key")
66
+ .description("Create a new API key")
67
+ .requiredOption("--name <name>", "Human-readable name for the key")
68
+ .requiredOption("--role <role>", `Role: ${API_KEY_ROLES.join(", ")}`)
69
+ .option("--scopes <scopes>", "Comma-separated additional scopes")
70
+ .option("--expires-in-days <days>", "Expiration in days (1-365)")
71
+ .option("--json", "Output as JSON")
72
+ .action(async (options) => {
73
+ try {
74
+ if (!API_KEY_ROLES.includes(options.role)) {
75
+ console.error(`Invalid role: ${options.role}`);
76
+ console.error(`Valid roles: ${API_KEY_ROLES.join(", ")}`);
77
+ process.exit(1);
78
+ }
79
+ const body = {
80
+ name: options.name,
81
+ role: options.role,
82
+ };
83
+ if (options.scopes) {
84
+ body.scopes = options.scopes.split(",").map((s) => s.trim());
85
+ }
86
+ if (options.expiresInDays) {
87
+ const days = parseInt(options.expiresInDays, 10);
88
+ if (isNaN(days) || days < 1 || days > 365) {
89
+ console.error("--expires-in-days must be between 1 and 365");
90
+ process.exit(1);
91
+ }
92
+ body.expiresInDays = days;
93
+ }
94
+ const result = await apiRequest("/api/auth/keys", {
95
+ method: "POST",
96
+ body,
97
+ });
98
+ if (options.json) {
99
+ console.log(JSON.stringify(result, null, 2));
100
+ return;
101
+ }
102
+ console.log("\n✅ API Key Created Successfully");
103
+ console.log("─".repeat(60));
104
+ console.log(`Name: ${result.name}`);
105
+ console.log(`Role: ${result.role}`);
106
+ console.log(`Key ID: ${result.id}`);
107
+ console.log(`Prefix: ${result.keyPrefix}`);
108
+ if (result.expiresAt) {
109
+ console.log(`Expires: ${new Date(result.expiresAt).toLocaleDateString()}`);
110
+ }
111
+ console.log("");
112
+ console.log("🔑 API KEY (store securely - shown only once):");
113
+ console.log("");
114
+ console.log(` ${result.plainTextKey}`);
115
+ console.log("");
116
+ console.log("⚠️ " + result.warning);
117
+ }
118
+ catch (error) {
119
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
120
+ process.exit(1);
121
+ }
122
+ });
123
+ authCommand
124
+ .command("revoke-key <id>")
125
+ .description("Revoke an API key")
126
+ .option("--json", "Output as JSON")
127
+ .action(async (id, options) => {
128
+ try {
129
+ const result = await apiRequest(`/api/auth/keys/${id}`, { method: "DELETE" });
130
+ if (options.json) {
131
+ console.log(JSON.stringify(result, null, 2));
132
+ return;
133
+ }
134
+ console.log(`\n✅ API Key Revoked: ${result.keyPrefix}...`);
135
+ console.log(` Revoked at: ${new Date(result.revokedAt).toLocaleString()}`);
136
+ }
137
+ catch (error) {
138
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
139
+ process.exit(1);
140
+ }
141
+ });
142
+ authCommand
143
+ .command("whoami")
144
+ .description("Show current authentication info")
145
+ .option("--json", "Output as JSON")
146
+ .action(async (options) => {
147
+ try {
148
+ const data = await apiRequest("/api/auth/whoami");
149
+ if (options.json) {
150
+ console.log(JSON.stringify(data, null, 2));
151
+ return;
152
+ }
153
+ console.log("\n🔐 Authentication Info");
154
+ console.log("─".repeat(40));
155
+ console.log(`Role: ${data.role}`);
156
+ console.log(`Key ID: ${data.keyId}`);
157
+ console.log(`Source: ${data.source}`);
158
+ if (data.scopes && data.scopes.length > 0) {
159
+ console.log(`Scopes: ${data.scopes.join(", ")}`);
160
+ }
161
+ console.log("");
162
+ console.log("Permissions:");
163
+ for (const perm of data.permissions) {
164
+ console.log(` • ${perm}`);
165
+ }
166
+ }
167
+ catch (error) {
168
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
169
+ process.exit(1);
170
+ }
171
+ });
172
+ authCommand
173
+ .command("permissions")
174
+ .description("Show cached permissions (5-min cache)")
175
+ .option("--refresh", "Force refresh from API")
176
+ .option("--json", "Output as JSON")
177
+ .action(async (options) => {
178
+ try {
179
+ if (options.refresh) {
180
+ clearPermissionsCache();
181
+ }
182
+ const perms = await getPermissions();
183
+ const cacheStatus = getCacheStatus();
184
+ if (options.json) {
185
+ console.log(JSON.stringify({
186
+ ...perms,
187
+ cache: cacheStatus,
188
+ }, null, 2));
189
+ return;
190
+ }
191
+ const cacheAge = cacheStatus.age ? Math.round(cacheStatus.age / 1000) : 0;
192
+ const expiresIn = cacheStatus.expiresIn ? Math.round(cacheStatus.expiresIn / 1000) : 0;
193
+ console.log("\n🔑 Cached Permissions");
194
+ console.log("─".repeat(50));
195
+ console.log(`Role: ${perms.role}`);
196
+ console.log(`Cache age: ${cacheAge}s (expires in ${expiresIn}s)`);
197
+ console.log("");
198
+ console.log("Permissions:");
199
+ for (const perm of perms.permissions) {
200
+ console.log(` • ${perm}`);
201
+ }
202
+ if (perms.knowledgeBases.length > 0) {
203
+ console.log("");
204
+ console.log("Knowledge Bases:");
205
+ for (const kb of perms.knowledgeBases) {
206
+ console.log(` • ${kb}`);
207
+ }
208
+ }
209
+ }
210
+ catch (error) {
211
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
212
+ process.exit(1);
213
+ }
214
+ });
215
+ authCommand
216
+ .command("can <permission>")
217
+ .description("Check if current key has a specific permission")
218
+ .option("--json", "Output as JSON")
219
+ .action(async (permission, options) => {
220
+ try {
221
+ const allowed = await hasPermission(permission);
222
+ if (options.json) {
223
+ console.log(JSON.stringify({ permission, allowed }));
224
+ return;
225
+ }
226
+ if (allowed) {
227
+ console.log(`✅ Permission granted: ${permission}`);
228
+ }
229
+ else {
230
+ console.log(`❌ Permission denied: ${permission}`);
231
+ process.exit(1);
232
+ }
233
+ }
234
+ catch (error) {
235
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
236
+ process.exit(1);
237
+ }
238
+ });
239
+ authCommand
240
+ .command("can-access-kb <kb>")
241
+ .description("Check if current key can access a knowledge base")
242
+ .option("--json", "Output as JSON")
243
+ .action(async (kb, options) => {
244
+ try {
245
+ const allowed = await canAccessKnowledgeBase(kb);
246
+ if (options.json) {
247
+ console.log(JSON.stringify({ knowledgeBase: kb, allowed }));
248
+ return;
249
+ }
250
+ if (allowed) {
251
+ console.log(`✅ Access granted to KB: ${kb}`);
252
+ }
253
+ else {
254
+ console.log(`❌ Access denied to KB: ${kb}`);
255
+ process.exit(1);
256
+ }
257
+ }
258
+ catch (error) {
259
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
260
+ process.exit(1);
261
+ }
262
+ });
263
+ authCommand
264
+ .command("login")
265
+ .description("Create a session token for this agent")
266
+ .requiredOption("--agent <name>", "Agent name (must be registered in Firestore)")
267
+ .option("--json", "Output as JSON")
268
+ .action(async (options) => {
269
+ try {
270
+ const config = getConfig();
271
+ if (!config.apiUrl || !config.apiKey) {
272
+ console.error("API not configured. Run: husky config set api-url <url> && husky config set api-key <key>");
273
+ process.exit(1);
274
+ }
275
+ const url = new URL("/api/auth/session", config.apiUrl);
276
+ const res = await fetch(url.toString(), {
277
+ method: "POST",
278
+ headers: {
279
+ "x-api-key": config.apiKey,
280
+ "Content-Type": "application/json",
281
+ },
282
+ body: JSON.stringify({ agent: options.agent }),
283
+ });
284
+ if (!res.ok) {
285
+ const error = await res.json().catch(() => ({ error: res.statusText }));
286
+ if (res.status === 404) {
287
+ console.error(`Agent '${options.agent}' not found. Register the agent first.`);
288
+ }
289
+ else {
290
+ console.error(`Login failed: ${error.message || error.error || `HTTP ${res.status}`}`);
291
+ }
292
+ process.exit(1);
293
+ }
294
+ const session = await res.json();
295
+ setSessionConfig(session);
296
+ if (options.json) {
297
+ console.log(JSON.stringify({
298
+ success: true,
299
+ agent: session.agent,
300
+ role: session.role,
301
+ expiresAt: session.expiresAt,
302
+ }, null, 2));
303
+ return;
304
+ }
305
+ const expiresAt = new Date(session.expiresAt);
306
+ console.log("\n✅ Session created");
307
+ console.log("─".repeat(40));
308
+ console.log(`Agent: ${session.agent}`);
309
+ console.log(`Role: ${session.role}`);
310
+ console.log(`Expires: ${expiresAt.toLocaleString()}`);
311
+ console.log("");
312
+ console.log("All API calls will now use this session token.");
313
+ }
314
+ catch (error) {
315
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
316
+ process.exit(1);
317
+ }
318
+ });
319
+ authCommand
320
+ .command("logout")
321
+ .description("Clear the current session token")
322
+ .option("--json", "Output as JSON")
323
+ .action(async (options) => {
324
+ const session = getSessionConfig();
325
+ if (!session) {
326
+ if (options.json) {
327
+ console.log(JSON.stringify({ success: false, message: "No active session" }));
328
+ }
329
+ else {
330
+ console.log("No active session to clear.");
331
+ }
332
+ return;
333
+ }
334
+ clearSessionConfig();
335
+ if (options.json) {
336
+ console.log(JSON.stringify({ success: true, agent: session.agent }));
337
+ return;
338
+ }
339
+ console.log(`✅ Session cleared for agent '${session.agent}'`);
340
+ });
341
+ authCommand
342
+ .command("session")
343
+ .description("Show current session status")
344
+ .option("--json", "Output as JSON")
345
+ .action(async (options) => {
346
+ const session = getSessionConfig();
347
+ if (!session || !session.token) {
348
+ if (options.json) {
349
+ console.log(JSON.stringify({ active: false }));
350
+ }
351
+ else {
352
+ console.log("No active session. Run: husky auth login --agent <name>");
353
+ }
354
+ return;
355
+ }
356
+ const expiresAt = session.expiresAt ? new Date(session.expiresAt) : null;
357
+ const now = new Date();
358
+ const isExpired = expiresAt ? expiresAt < now : true;
359
+ const expiresInMs = expiresAt ? expiresAt.getTime() - now.getTime() : 0;
360
+ const expiresInMinutes = Math.max(0, Math.floor(expiresInMs / 60000));
361
+ if (options.json) {
362
+ console.log(JSON.stringify({
363
+ active: !isExpired,
364
+ agent: session.agent,
365
+ role: session.role,
366
+ expiresAt: session.expiresAt,
367
+ expired: isExpired,
368
+ expiresInMinutes,
369
+ }, null, 2));
370
+ return;
371
+ }
372
+ console.log("\n🔐 Session Status");
373
+ console.log("─".repeat(40));
374
+ console.log(`Agent: ${session.agent || "(unknown)"}`);
375
+ console.log(`Role: ${session.role || "(unknown)"}`);
376
+ if (isExpired) {
377
+ console.log(`Status: 🔴 EXPIRED`);
378
+ console.log(`Expired: ${expiresAt?.toLocaleString() || "(unknown)"}`);
379
+ console.log("");
380
+ console.log("Run: husky auth refresh --agent <name>");
381
+ }
382
+ else {
383
+ console.log(`Status: 🟢 ACTIVE`);
384
+ console.log(`Expires: ${expiresAt?.toLocaleString()} (${expiresInMinutes} minutes)`);
385
+ }
386
+ });
387
+ authCommand
388
+ .command("refresh")
389
+ .description("Refresh the session token")
390
+ .option("--agent <name>", "Agent name (uses current session agent if not specified)")
391
+ .option("--json", "Output as JSON")
392
+ .action(async (options) => {
393
+ try {
394
+ const config = getConfig();
395
+ if (!config.apiUrl || !config.apiKey) {
396
+ console.error("API not configured. Run: husky config set api-url <url> && husky config set api-key <key>");
397
+ process.exit(1);
398
+ }
399
+ const currentSession = getSessionConfig();
400
+ const agentName = options.agent || currentSession?.agent;
401
+ if (!agentName) {
402
+ console.error("No agent specified and no active session. Use: husky auth refresh --agent <name>");
403
+ process.exit(1);
404
+ }
405
+ const url = new URL("/api/auth/session", config.apiUrl);
406
+ const res = await fetch(url.toString(), {
407
+ method: "POST",
408
+ headers: {
409
+ "x-api-key": config.apiKey,
410
+ "Content-Type": "application/json",
411
+ },
412
+ body: JSON.stringify({ agent: agentName }),
413
+ });
414
+ if (!res.ok) {
415
+ const error = await res.json().catch(() => ({ error: res.statusText }));
416
+ console.error(`Refresh failed: ${error.message || error.error || `HTTP ${res.status}`}`);
417
+ process.exit(1);
418
+ }
419
+ const session = await res.json();
420
+ setSessionConfig(session);
421
+ if (options.json) {
422
+ console.log(JSON.stringify({
423
+ success: true,
424
+ agent: session.agent,
425
+ role: session.role,
426
+ expiresAt: session.expiresAt,
427
+ }, null, 2));
428
+ return;
429
+ }
430
+ const expiresAt = new Date(session.expiresAt);
431
+ console.log(`✅ Session refreshed for '${session.agent}' (expires: ${expiresAt.toLocaleString()})`);
432
+ }
433
+ catch (error) {
434
+ console.error(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
435
+ process.exit(1);
436
+ }
437
+ });