@hive3/cli 0.1.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.
@@ -0,0 +1,493 @@
1
+ // @ts-check
2
+
3
+ import { readFile } from "node:fs/promises";
4
+
5
+ import { createApiClient, HiveApiError } from "./api-client.js";
6
+ import { loadConfig } from "./config.js";
7
+
8
+ function writeLine(stream, message = "") {
9
+ stream.write(`${message}\n`);
10
+ }
11
+
12
+ function writeJson(stream, value) {
13
+ writeLine(stream, JSON.stringify(value, null, 2));
14
+ }
15
+
16
+ function requiredFlagValue(flag, value) {
17
+ if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
18
+ return value;
19
+ }
20
+
21
+ function parseBoolean(value, flag) {
22
+ if (value === "true" || value === "1" || value === "yes") return true;
23
+ if (value === "false" || value === "0" || value === "no") return false;
24
+ throw new Error(`${flag} must be true or false`);
25
+ }
26
+
27
+ async function readJsonFile(file) {
28
+ const parsed = JSON.parse(await readFile(file, "utf8"));
29
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
30
+ throw new Error(`${file} must contain a JSON object`);
31
+ }
32
+ return parsed;
33
+ }
34
+
35
+ async function authenticatedClient(deps) {
36
+ const config = await loadConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
37
+ if (!config) throw new HiveApiError("Not logged in. Run hive login first.", { code: "auth_required", status: 401 });
38
+ return createApiClient({ apiBaseUrl: config.apiBaseUrl, apiKey: config.apiKey, fetch: deps.fetch });
39
+ }
40
+
41
+ async function parseWorkflowPayload(args, allowedFlags = []) {
42
+ const payload = {};
43
+ for (let index = 0; index < args.length; index += 1) {
44
+ const flag = args[index];
45
+ if (flag === "--file") {
46
+ index += 1;
47
+ Object.assign(payload, await readJsonFile(requiredFlagValue(flag, args[index])));
48
+ } else if (flag === "--enroll" || flag === "--attended") {
49
+ index += 1;
50
+ payload[flag.slice(2)] = parseBoolean(requiredFlagValue(flag, args[index]), flag);
51
+ } else if (allowedFlags.includes(flag)) {
52
+ index += 1;
53
+ payload[flag.slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] =
54
+ requiredFlagValue(flag, args[index]);
55
+ } else {
56
+ throw new Error(`Unknown workflow option: ${flag}`);
57
+ }
58
+ }
59
+ return payload;
60
+ }
61
+
62
+ function parseNotificationListOptions(args) {
63
+ const query = {};
64
+ for (let index = 0; index < args.length; index += 1) {
65
+ const flag = args[index];
66
+ if (flag === "--limit") {
67
+ index += 1;
68
+ query.limit = Number(requiredFlagValue(flag, args[index]));
69
+ if (!Number.isFinite(query.limit) || query.limit <= 0) throw new Error("--limit must be a positive number");
70
+ } else if (flag === "--offset") {
71
+ index += 1;
72
+ query.offset = Number(requiredFlagValue(flag, args[index]));
73
+ if (!Number.isFinite(query.offset) || query.offset < 0) throw new Error("--offset must be zero or greater");
74
+ } else if (flag === "--unread-only") {
75
+ query.unreadOnly = true;
76
+ } else {
77
+ throw new Error(`Unknown notifications list option: ${flag}`);
78
+ }
79
+ }
80
+ return query;
81
+ }
82
+
83
+ async function runNotifications(args, deps) {
84
+ const [action, ...rest] = args;
85
+ const client = await authenticatedClient(deps);
86
+ if (action === "list") {
87
+ writeJson(deps.stdout, await client.listNotifications(parseNotificationListOptions(rest)));
88
+ return;
89
+ }
90
+ if (action === "read") {
91
+ const notificationId = requiredFlagValue("notification id", rest[0]);
92
+ if (rest.length > 1) throw new Error(`Unknown notifications read option: ${rest[1]}`);
93
+ writeJson(deps.stdout, await client.markNotificationRead(notificationId));
94
+ return;
95
+ }
96
+ if (action === "read-all") {
97
+ if (rest.length > 0) throw new Error(`Unknown notifications read-all option: ${rest[0]}`);
98
+ writeJson(deps.stdout, await client.markAllNotificationsRead());
99
+ return;
100
+ }
101
+ if (action === "delete") {
102
+ const notificationId = requiredFlagValue("notification id", rest[0]);
103
+ if (rest.length > 1) throw new Error(`Unknown notifications delete option: ${rest[1]}`);
104
+ writeJson(deps.stdout, await client.removeNotification(notificationId));
105
+ return;
106
+ }
107
+ if (action === "mutes") {
108
+ const muteAction = rest[0] ?? "list";
109
+ if (muteAction === "list") {
110
+ if (rest.length > 1) throw new Error(`Unknown notifications mutes list option: ${rest[1]}`);
111
+ writeJson(deps.stdout, await client.listNotificationMutes());
112
+ return;
113
+ }
114
+ if (muteAction === "set") {
115
+ let muted;
116
+ let scope;
117
+ let scopeId;
118
+ for (let index = 1; index < rest.length; index += 1) {
119
+ const flag = rest[index];
120
+ if (flag === "--scope") {
121
+ index += 1; scope = requiredFlagValue(flag, rest[index]);
122
+ } else if (flag === "--scope-id") {
123
+ index += 1; scopeId = requiredFlagValue(flag, rest[index]);
124
+ } else if (flag === "--muted") {
125
+ index += 1; muted = parseBoolean(requiredFlagValue(flag, rest[index]), flag);
126
+ } else {
127
+ throw new Error(`Unknown notifications mutes set option: ${flag}`);
128
+ }
129
+ }
130
+ if (!scope || muted === undefined) throw new Error("--scope and --muted are required");
131
+ writeJson(deps.stdout, await client.setNotificationMute({ muted, scope, scopeId }));
132
+ return;
133
+ }
134
+ }
135
+ throw new Error(`Unknown notifications action: ${action || ""}`.trim());
136
+ }
137
+
138
+ function parseCommentListOptions(args) {
139
+ const query = {};
140
+ for (let index = 0; index < args.length; index += 1) {
141
+ const flag = args[index];
142
+ if (flag === "--post-id") {
143
+ index += 1; query.postId = requiredFlagValue(flag, args[index]);
144
+ } else if (flag === "--limit") {
145
+ index += 1; query.limit = Number(requiredFlagValue(flag, args[index]));
146
+ if (!Number.isFinite(query.limit) || query.limit <= 0) throw new Error("--limit must be a positive number");
147
+ } else if (flag === "--cursor") {
148
+ index += 1; query.cursor = requiredFlagValue(flag, args[index]);
149
+ } else {
150
+ throw new Error(`Unknown comments list option: ${flag}`);
151
+ }
152
+ }
153
+ if (!query.postId) throw new Error("--post-id is required");
154
+ return query;
155
+ }
156
+
157
+ async function runComments(args, deps) {
158
+ const [action, ...rest] = args;
159
+ const client = await authenticatedClient(deps);
160
+ if (action === "list") {
161
+ writeJson(deps.stdout, await client.listComments(parseCommentListOptions(rest)));
162
+ return;
163
+ }
164
+ if (action === "create") {
165
+ let content;
166
+ let imageUrl;
167
+ let postId;
168
+ for (let index = 0; index < rest.length; index += 1) {
169
+ const flag = rest[index];
170
+ if (flag === "--post-id") {
171
+ index += 1; postId = requiredFlagValue(flag, rest[index]);
172
+ } else if (flag === "--content") {
173
+ index += 1; content = requiredFlagValue(flag, rest[index]);
174
+ } else if (flag === "--image-url") {
175
+ index += 1; imageUrl = requiredFlagValue(flag, rest[index]);
176
+ } else {
177
+ throw new Error(`Unknown comments create option: ${flag}`);
178
+ }
179
+ }
180
+ if (!postId || !content) throw new Error("--post-id and --content are required");
181
+ writeJson(deps.stdout, await client.createComment(postId, { content, imageUrl }));
182
+ return;
183
+ }
184
+ if (action === "update") {
185
+ const commentId = requiredFlagValue("comment id", rest[0]);
186
+ if (rest[1] !== "--content") throw new Error("--content is required");
187
+ const content = requiredFlagValue("--content", rest[2]);
188
+ if (rest.length > 3) throw new Error(`Unknown comments update option: ${rest[3]}`);
189
+ writeJson(deps.stdout, await client.updateComment(commentId, { content }));
190
+ return;
191
+ }
192
+ if (action === "delete") {
193
+ const commentId = requiredFlagValue("comment id", rest[0]);
194
+ if (rest.length > 1) throw new Error(`Unknown comments delete option: ${rest[1]}`);
195
+ writeJson(deps.stdout, await client.removeComment(commentId));
196
+ return;
197
+ }
198
+ if (action === "like") {
199
+ const commentId = requiredFlagValue("comment id", rest[0]);
200
+ if (rest.length > 1) throw new Error(`Unknown comments like option: ${rest[1]}`);
201
+ writeJson(deps.stdout, await client.toggleCommentLike(commentId));
202
+ return;
203
+ }
204
+ throw new Error(`Unknown comments action: ${action || ""}`.trim());
205
+ }
206
+
207
+ async function runPostsExtended(args, deps) {
208
+ const [action, ...rest] = args;
209
+ if (action !== "like") return false;
210
+ const postId = requiredFlagValue("post id", rest[0]);
211
+ if (rest.length > 1) throw new Error(`Unknown posts like option: ${rest[1]}`);
212
+ writeJson(deps.stdout, await (await authenticatedClient(deps)).togglePostLike(postId));
213
+ return true;
214
+ }
215
+
216
+ async function runEventsWorkflow(args, deps) {
217
+ const [action, ...rest] = args;
218
+ const client = await authenticatedClient(deps);
219
+ if (action === "participants") {
220
+ const eventId = requiredFlagValue("event id", rest[0]);
221
+ if (rest.length > 1) throw new Error(`Unknown events participants option: ${rest[1]}`);
222
+ writeJson(deps.stdout, await client.workflowGet(`events/${encodeURIComponent(eventId)}/participants`));
223
+ return true;
224
+ }
225
+ if (action === "rsvp") {
226
+ const eventId = requiredFlagValue("event id", rest[0]);
227
+ writeJson(deps.stdout, await client.workflowPost(
228
+ `events/${encodeURIComponent(eventId)}/rsvp`,
229
+ await parseWorkflowPayload(rest.slice(1)),
230
+ ));
231
+ return true;
232
+ }
233
+ if (action === "approve" || action === "deny") {
234
+ const eventId = requiredFlagValue("event id", rest[0]);
235
+ const enrollmentId = requiredFlagValue("enrollment id", rest[1]);
236
+ if (rest.length > 2) throw new Error(`Unknown events ${action} option: ${rest[2]}`);
237
+ writeJson(deps.stdout, await client.workflowPatch(
238
+ `events/${encodeURIComponent(eventId)}/participants/${encodeURIComponent(enrollmentId)}`,
239
+ { accepted: action === "approve" },
240
+ ));
241
+ return true;
242
+ }
243
+ if (action === "attendance") {
244
+ const eventId = requiredFlagValue("event id", rest[0]);
245
+ const enrollmentId = requiredFlagValue("enrollment id", rest[1]);
246
+ const payload = await parseWorkflowPayload(rest.slice(2));
247
+ payload.enrollmentId = enrollmentId;
248
+ writeJson(deps.stdout, await client.workflowPost(`events/${encodeURIComponent(eventId)}/attendance`, payload));
249
+ return true;
250
+ }
251
+ return false;
252
+ }
253
+
254
+ async function runCoursesWorkflow(args, deps) {
255
+ const [action, ...rest] = args;
256
+ const client = await authenticatedClient(deps);
257
+ if (action === "enrollments") {
258
+ const courseId = requiredFlagValue("course id", rest[0]);
259
+ if (rest.length > 1) throw new Error(`Unknown courses enrollments option: ${rest[1]}`);
260
+ writeJson(deps.stdout, await client.workflowGet(`courses/${encodeURIComponent(courseId)}/enrollments`));
261
+ return true;
262
+ }
263
+ if (action === "enroll") {
264
+ const courseId = requiredFlagValue("course id", rest[0]);
265
+ writeJson(deps.stdout, await client.workflowPost(
266
+ `courses/${encodeURIComponent(courseId)}/enrollment`,
267
+ await parseWorkflowPayload(rest.slice(1)),
268
+ ));
269
+ return true;
270
+ }
271
+ if (action === "approve" || action === "deny") {
272
+ const courseId = requiredFlagValue("course id", rest[0]);
273
+ const personId = requiredFlagValue("person id", rest[1]);
274
+ if (rest.length > 2) throw new Error(`Unknown courses ${action} option: ${rest[2]}`);
275
+ writeJson(deps.stdout, await client.workflowPatch(
276
+ `courses/${encodeURIComponent(courseId)}/enrollments/${encodeURIComponent(personId)}`,
277
+ { accepted: action === "approve" },
278
+ ));
279
+ return true;
280
+ }
281
+ if (action === "complete") {
282
+ const courseId = requiredFlagValue("course id", rest[0]);
283
+ const lessonId = requiredFlagValue("lesson id", rest[1]);
284
+ if (rest.length > 2) throw new Error(`Unknown courses complete option: ${rest[2]}`);
285
+ writeJson(deps.stdout, await client.workflowPost(
286
+ `courses/${encodeURIComponent(courseId)}/lessons/${encodeURIComponent(lessonId)}/complete`,
287
+ {},
288
+ ));
289
+ return true;
290
+ }
291
+ return false;
292
+ }
293
+
294
+ async function runQuestsWorkflow(args, deps) {
295
+ const [action, ...rest] = args;
296
+ const client = await authenticatedClient(deps);
297
+ if (action === "enrollments") {
298
+ const questId = requiredFlagValue("quest id", rest[0]);
299
+ if (rest.length > 1) throw new Error(`Unknown quests enrollments option: ${rest[1]}`);
300
+ writeJson(deps.stdout, await client.workflowGet(`quests/${encodeURIComponent(questId)}/enrollments`));
301
+ return true;
302
+ }
303
+ if (action === "enroll") {
304
+ const questId = requiredFlagValue("quest id", rest[0]);
305
+ writeJson(deps.stdout, await client.workflowPost(
306
+ `quests/${encodeURIComponent(questId)}/enrollment`,
307
+ await parseWorkflowPayload(rest.slice(1)),
308
+ ));
309
+ return true;
310
+ }
311
+ if (action === "approve" || action === "deny") {
312
+ const questId = requiredFlagValue("quest id", rest[0]);
313
+ const enrollmentId = requiredFlagValue("enrollment id", rest[1]);
314
+ if (rest.length > 2) throw new Error(`Unknown quests ${action} option: ${rest[2]}`);
315
+ writeJson(deps.stdout, await client.workflowPatch(
316
+ `quests/${encodeURIComponent(questId)}/enrollments/${encodeURIComponent(enrollmentId)}`,
317
+ { accepted: action === "approve" },
318
+ ));
319
+ return true;
320
+ }
321
+ if (action === "evidence") return await runQuestEvidence(rest, client, deps);
322
+ return false;
323
+ }
324
+
325
+ async function runQuestEvidence(args, client, deps) {
326
+ const [action, ...rest] = args;
327
+ if (action === "list") {
328
+ const questId = requiredFlagValue("quest id", rest[0]);
329
+ const query = {};
330
+ if (rest[1] === "--status") query.status = requiredFlagValue("--status", rest[2]);
331
+ else if (rest.length > 1) throw new Error(`Unknown quests evidence list option: ${rest[1]}`);
332
+ writeJson(deps.stdout, await client.workflowGet(`quests/${encodeURIComponent(questId)}/evidence`, query));
333
+ return true;
334
+ }
335
+ if (action === "submit") {
336
+ const questId = requiredFlagValue("quest id", rest[0]);
337
+ const payload = await parseWorkflowPayload(rest.slice(1), ["--objective-id", "--content"]);
338
+ if (!payload.objectiveId) throw new Error("--objective-id is required");
339
+ writeJson(deps.stdout, await client.workflowPost(`quests/${encodeURIComponent(questId)}/evidence`, payload));
340
+ return true;
341
+ }
342
+ if (action === "approve" || action === "deny") {
343
+ const questId = requiredFlagValue("quest id", rest[0]);
344
+ const evidenceId = requiredFlagValue("evidence id", rest[1]);
345
+ if (rest.length > 2) throw new Error(`Unknown quests evidence ${action} option: ${rest[2]}`);
346
+ writeJson(deps.stdout, await client.workflowPatch(
347
+ `quests/${encodeURIComponent(questId)}/evidence/${encodeURIComponent(evidenceId)}`,
348
+ { status: action === "approve" ? "approved" : "denied" },
349
+ ));
350
+ return true;
351
+ }
352
+ throw new Error(`Unknown quests evidence action: ${action || ""}`.trim());
353
+ }
354
+
355
+ async function runJobsWorkflow(args, deps) {
356
+ const [action, ...rest] = args;
357
+ const client = await authenticatedClient(deps);
358
+ if (action === "apply") {
359
+ const jobId = requiredFlagValue("job id", rest[0]);
360
+ const payload = await parseWorkflowPayload(rest.slice(1));
361
+ if (!payload.resume) throw new Error("--file JSON must include resume");
362
+ writeJson(deps.stdout, await client.workflowPost(`jobs/${encodeURIComponent(jobId)}/applications`, payload));
363
+ return true;
364
+ }
365
+ if (action === "applications") {
366
+ const jobId = rest[0];
367
+ if (rest.length > 1) throw new Error(`Unknown jobs applications option: ${rest[1]}`);
368
+ const path = jobId ? `jobs/${encodeURIComponent(jobId)}/applications` : "jobs/applications";
369
+ writeJson(deps.stdout, await client.workflowGet(path));
370
+ return true;
371
+ }
372
+ if (action === "status") {
373
+ const applicationId = requiredFlagValue("application id", rest[0]);
374
+ if (rest[1] !== "--status") throw new Error("--status is required");
375
+ const status = requiredFlagValue("--status", rest[2]);
376
+ if (rest.length > 3) throw new Error(`Unknown jobs status option: ${rest[3]}`);
377
+ writeJson(deps.stdout, await client.workflowPatch(`job-applications/${encodeURIComponent(applicationId)}`, { status }));
378
+ return true;
379
+ }
380
+ return false;
381
+ }
382
+
383
+ function parseMembershipOptions(action, args) {
384
+ const communityId = requiredFlagValue("community id", args[0]);
385
+ let message;
386
+ for (let index = 1; index < args.length; index += 1) {
387
+ const flag = args[index];
388
+ if (flag === "--message") {
389
+ index += 1; message = requiredFlagValue(flag, args[index]);
390
+ } else {
391
+ throw new Error(`Unknown communities ${action} option: ${flag}`);
392
+ }
393
+ }
394
+ return { communityId, payload: { action, message } };
395
+ }
396
+
397
+ function parseAccessOptions(args) {
398
+ const communityId = requiredFlagValue("community id", args[0]);
399
+ let accessType;
400
+ let subscriptionId;
401
+ for (let index = 1; index < args.length; index += 1) {
402
+ const flag = args[index];
403
+ if (flag === "--type") {
404
+ index += 1; accessType = requiredFlagValue(flag, args[index]);
405
+ } else if (flag === "--subscription-id") {
406
+ index += 1; subscriptionId = requiredFlagValue(flag, args[index]);
407
+ } else {
408
+ throw new Error(`Unknown communities access option: ${flag}`);
409
+ }
410
+ }
411
+ if (!accessType) throw new Error("--type is required");
412
+ return { communityId, payload: { accessType, subscriptionId } };
413
+ }
414
+
415
+ async function runCommunities(args, deps) {
416
+ const [action, ...rest] = args;
417
+ const client = await authenticatedClient(deps);
418
+ if (action === "join" || action === "apply" || action === "leave") {
419
+ const parsed = parseMembershipOptions(action, rest);
420
+ writeJson(deps.stdout, await client.communityMembership(parsed.communityId, parsed.payload));
421
+ return;
422
+ }
423
+ if (action === "applications") {
424
+ const communityId = requiredFlagValue("community id", rest[0]);
425
+ if (rest.length > 1) throw new Error(`Unknown communities applications option: ${rest[1]}`);
426
+ writeJson(deps.stdout, await client.listCommunityApplications(communityId));
427
+ return;
428
+ }
429
+ if (action === "approve" || action === "deny") {
430
+ const applicationId = requiredFlagValue("application id", rest[0]);
431
+ if (rest.length > 1) throw new Error(`Unknown communities ${action} option: ${rest[1]}`);
432
+ writeJson(deps.stdout, await client.reviewCommunityApplication(
433
+ applicationId,
434
+ action === "approve" ? "accepted" : "rejected",
435
+ ));
436
+ return;
437
+ }
438
+ if (action === "members") {
439
+ const communityId = requiredFlagValue("community id", rest[0]);
440
+ if (rest.length > 1) throw new Error(`Unknown communities members option: ${rest[1]}`);
441
+ writeJson(deps.stdout, await client.listCommunityMembers(communityId));
442
+ return;
443
+ }
444
+ if (action === "role") {
445
+ const communityId = requiredFlagValue("community id", rest[0]);
446
+ const personId = requiredFlagValue("person id", rest[1]);
447
+ if (rest[2] !== "--role") throw new Error("--role is required");
448
+ const role = requiredFlagValue("--role", rest[3]);
449
+ if (role !== "admin" && role !== "moderator" && role !== "member") {
450
+ throw new Error("--role must be admin, moderator, or member");
451
+ }
452
+ if (rest.length > 4) throw new Error(`Unknown communities role option: ${rest[4]}`);
453
+ writeJson(deps.stdout, await client.setCommunityRole(communityId, personId, role));
454
+ return;
455
+ }
456
+ if (action === "remove-member") {
457
+ const communityId = requiredFlagValue("community id", rest[0]);
458
+ const personId = requiredFlagValue("person id", rest[1]);
459
+ if (rest[2] !== "--confirm") throw new Error("--confirm is required");
460
+ const confirmation = requiredFlagValue("--confirm", rest[3]);
461
+ if (confirmation !== personId) throw new Error("--confirm must exactly match the member person id");
462
+ if (rest.length > 4) throw new Error(`Unknown communities remove-member option: ${rest[4]}`);
463
+ writeJson(deps.stdout, await client.removeCommunityMember(communityId, personId));
464
+ return;
465
+ }
466
+ if (action === "access") {
467
+ const parsed = parseAccessOptions(rest);
468
+ writeJson(deps.stdout, await client.updateCommunityAccess(parsed.communityId, parsed.payload));
469
+ return;
470
+ }
471
+ throw new Error(`Unknown communities action: ${action || ""}`.trim());
472
+ }
473
+
474
+ export async function runExtendedCommand(command, args, deps) {
475
+ if (command === "notifications") {
476
+ await runNotifications(args, deps);
477
+ return true;
478
+ }
479
+ if (command === "comments") {
480
+ await runComments(args, deps);
481
+ return true;
482
+ }
483
+ if (command === "communities") {
484
+ await runCommunities(args, deps);
485
+ return true;
486
+ }
487
+ if (command === "events") return await runEventsWorkflow(args, deps);
488
+ if (command === "courses") return await runCoursesWorkflow(args, deps);
489
+ if (command === "quests") return await runQuestsWorkflow(args, deps);
490
+ if (command === "jobs") return await runJobsWorkflow(args, deps);
491
+ if (command === "posts") return await runPostsExtended(args, deps);
492
+ return false;
493
+ }
package/src/login.js ADDED
@@ -0,0 +1,176 @@
1
+ // @ts-check
2
+
3
+ import { spawn } from "node:child_process";
4
+
5
+ import { HiveApiError, normalizeBaseUrl, postJson } from "./api-client.js";
6
+ import { saveCredential } from "./config.js";
7
+
8
+ export const DEFAULT_API_BASE_URL = "https://app.hive3.tech/api/v1";
9
+ export const DEFAULT_APP_URL = "https://app.hive3.tech";
10
+ export const DEFAULT_LABEL = "Hive CLI";
11
+ export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
12
+
13
+ export function loginUsage() {
14
+ return [
15
+ "Usage: hive login [options]",
16
+ "",
17
+ "Options:",
18
+ " --api-url <url> Public API base URL",
19
+ " --app-url <url> Browser app URL for approval",
20
+ " --label <label> Local credential label",
21
+ " --scope <scope> Requested API scope, repeatable",
22
+ " --timeout-ms <ms> Login polling timeout",
23
+ " --no-open Print the URL without opening a browser",
24
+ " -h, --help Show help",
25
+ ].join("\n");
26
+ }
27
+
28
+ function requiredFlagValue(flag, value) {
29
+ if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
30
+ return value;
31
+ }
32
+
33
+ export function parseLoginArgs(args, env = process.env) {
34
+ const options = {
35
+ apiBaseUrl: env.HIVE_API_URL || DEFAULT_API_BASE_URL,
36
+ appUrl: env.HIVE_APP_URL || DEFAULT_APP_URL,
37
+ label: DEFAULT_LABEL,
38
+ noOpen: false,
39
+ scopes: [],
40
+ timeoutMs: DEFAULT_TIMEOUT_MS,
41
+ };
42
+
43
+ for (let index = 0; index < args.length; index += 1) {
44
+ const flag = args[index];
45
+ if (flag === "--no-open") {
46
+ options.noOpen = true;
47
+ } else if (flag === "--api-url") {
48
+ index += 1;
49
+ options.apiBaseUrl = requiredFlagValue(flag, args[index]);
50
+ } else if (flag === "--app-url") {
51
+ index += 1;
52
+ options.appUrl = requiredFlagValue(flag, args[index]);
53
+ } else if (flag === "--label") {
54
+ index += 1;
55
+ options.label = requiredFlagValue(flag, args[index]);
56
+ } else if (flag === "--scope") {
57
+ index += 1;
58
+ options.scopes.push(requiredFlagValue(flag, args[index]));
59
+ } else if (flag === "--timeout-ms") {
60
+ index += 1;
61
+ options.timeoutMs = Number(requiredFlagValue(flag, args[index]));
62
+ } else if (flag === "--help" || flag === "-h") {
63
+ return { help: true, options };
64
+ } else {
65
+ throw new Error(`Unknown login option: ${flag}`);
66
+ }
67
+ }
68
+
69
+ if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
70
+ throw new Error("--timeout-ms must be a positive number");
71
+ }
72
+ return { help: false, options };
73
+ }
74
+
75
+ export function isSafeBrowserUrl(url) {
76
+ let parsed;
77
+ try {
78
+ parsed = new URL(url);
79
+ } catch {
80
+ return false;
81
+ }
82
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
83
+ // Refuse shell/command metacharacters so the URL can never be reinterpreted
84
+ // by the platform launcher (notably `cmd /c start` on Windows).
85
+ return !/[\s"'`;&|<>^$()]/.test(url);
86
+ }
87
+
88
+ export function openBrowser(url, platform = process.platform, spawnImpl = spawn) {
89
+ if (!isSafeBrowserUrl(url)) return false;
90
+ // win32 uses rundll32's FileProtocolHandler instead of `cmd /c start` so the
91
+ // URL is never subject to cmd.exe %VAR% environment expansion.
92
+ const command = platform === "darwin" ? "open" : platform === "win32" ? "rundll32" : "xdg-open";
93
+ const args = platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
94
+ const child = spawnImpl(command, args, { detached: true, stdio: "ignore" });
95
+ // Missing launcher binaries (headless Linux, containers) emit an async
96
+ // "error"; without a listener that crashes the process mid-login.
97
+ child.on("error", () => {});
98
+ child.unref();
99
+ return true;
100
+ }
101
+
102
+ export function sleep(ms) {
103
+ return new Promise(resolve => setTimeout(resolve, ms));
104
+ }
105
+
106
+ function defaultDeps() {
107
+ return {
108
+ env: process.env,
109
+ fetch: globalThis.fetch,
110
+ homeDir: undefined,
111
+ now: () => Date.now(),
112
+ openBrowser,
113
+ platform: process.platform,
114
+ sleep,
115
+ stdout: process.stdout,
116
+ };
117
+ }
118
+
119
+ function writeLine(stream, message = "") {
120
+ stream.write(`${message}\n`);
121
+ }
122
+
123
+ export async function login(options, overrides = {}) {
124
+ const deps = { ...defaultDeps(), ...overrides };
125
+ const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl);
126
+ const start = await postJson(deps.fetch, `${apiBaseUrl}/cli/auth/start`, {
127
+ appUrl: options.appUrl,
128
+ label: options.label,
129
+ scopes: options.scopes.length > 0 ? options.scopes : undefined,
130
+ });
131
+ const data = start.data;
132
+ // A malformed server response must not turn the poll loop into a busy loop
133
+ // (NaN/0 sleeps) or a hammering one: fall back to a sane 2s interval.
134
+ const rawPollIntervalMs = Number(data.pollIntervalMs);
135
+ const pollIntervalMs = Number.isFinite(rawPollIntervalMs) && rawPollIntervalMs >= 500 ? rawPollIntervalMs : 2000;
136
+
137
+ writeLine(deps.stdout, `Open this URL to approve Hive CLI access: ${data.approvalUrl}`);
138
+ writeLine(deps.stdout, `Code: ${data.code} (type it on the approval page)`);
139
+ if (!options.noOpen) deps.openBrowser(data.approvalUrl, deps.platform);
140
+
141
+ const deadline = deps.now() + options.timeoutMs;
142
+ while (deps.now() <= deadline) {
143
+ let poll;
144
+ try {
145
+ poll = await postJson(deps.fetch, `${apiBaseUrl}/cli/auth/poll`, {
146
+ pollToken: data.pollToken,
147
+ requestId: data.requestId,
148
+ });
149
+ } catch (error) {
150
+ if (error instanceof HiveApiError && error.status === 429) {
151
+ // Rate-limited (shared IP / NAT): honor Retry-After and keep polling.
152
+ const retryAfterMs = Number(error.retryAfterSeconds) * 1000;
153
+ await deps.sleep(Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? Math.max(retryAfterMs, pollIntervalMs) : pollIntervalMs);
154
+ continue;
155
+ }
156
+ throw error;
157
+ }
158
+ const result = poll.data;
159
+ if (result.status === "approved") {
160
+ const configPath = await saveCredential(
161
+ result.credential,
162
+ { ...options, apiBaseUrl },
163
+ { env: deps.env, homeDir: deps.homeDir, platform: deps.platform },
164
+ );
165
+ writeLine(deps.stdout, `Hive CLI authenticated as API key ${result.credential.keyPrefix}.`);
166
+ writeLine(deps.stdout, `Credential stored at ${configPath}.`);
167
+ return { configPath, keyPrefix: result.credential.keyPrefix, status: "approved" };
168
+ }
169
+ if (result.status === "denied") throw new Error("Hive CLI login was denied in the browser.");
170
+ if (result.status === "expired") throw new Error("Hive CLI login expired. Run hive login again.");
171
+ if (result.status === "completed") throw new Error("Hive CLI login was already completed. Run hive login again.");
172
+ if (result.status === "not_found") throw new Error("Hive CLI login request was not found.");
173
+ await deps.sleep(pollIntervalMs);
174
+ }
175
+ throw new Error("Hive CLI login timed out.");
176
+ }