@hive3/cli 0.3.0 → 0.5.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/src/config.js CHANGED
@@ -29,6 +29,7 @@ function configDeps(overrides = {}) {
29
29
  env: process.env,
30
30
  homeDir: os.homedir(),
31
31
  platform: process.platform,
32
+ uid: typeof process.getuid === "function" ? process.getuid() : undefined,
32
33
  };
33
34
  for (const [key, value] of Object.entries(overrides)) {
34
35
  if (value !== undefined) deps[key] = value;
@@ -38,11 +39,11 @@ function configDeps(overrides = {}) {
38
39
 
39
40
  function assertStoredConfig(value) {
40
41
  if (!value || typeof value !== "object" || Array.isArray(value)) {
41
- throw new Error("Hive CLI config is invalid. Run hive login again.");
42
+ throw new Error("Hive CLI config is invalid. Run hive3 login again.");
42
43
  }
43
44
  const record = /** @type {Record<string, unknown>} */ (value);
44
45
  if (typeof record.apiBaseUrl !== "string" || typeof record.apiKey !== "string") {
45
- throw new Error("Hive CLI config is missing credentials. Run hive login again.");
46
+ throw new Error("Hive CLI config is missing credentials. Run hive3 login again.");
46
47
  }
47
48
  return /** @type {StoredHiveConfig} */ ({
48
49
  apiBaseUrl: record.apiBaseUrl,
@@ -53,24 +54,71 @@ function assertStoredConfig(value) {
53
54
  });
54
55
  }
55
56
 
57
+ /**
58
+ * Another local user who owns or can write the config could swap in their own API URL and
59
+ * key, silently redirecting every command (and uploaded file) to a server they control.
60
+ */
61
+ function assertPrivateConfigFile(file, info, uid) {
62
+ if (info.uid !== uid) {
63
+ throw new Error(`Refusing to load Hive CLI config ${file}: it is not owned by the current user. Remove it and run hive3 login again.`);
64
+ }
65
+ if ((info.mode & 0o022) !== 0) {
66
+ throw new Error(`Refusing to load Hive CLI config ${file}: it is writable by other users. Run chmod 600 on it, or remove it and run hive3 login again.`);
67
+ }
68
+ }
69
+
56
70
  export async function loadConfig(overrides = {}) {
57
71
  const deps = configDeps(overrides);
58
72
  const file = configPath(deps.env, deps.platform, deps.homeDir);
73
+ let handle;
59
74
  try {
60
- const text = await fs.readFile(file, "utf8");
61
- return assertStoredConfig(JSON.parse(text));
75
+ handle = await fs.open(file, "r");
62
76
  } catch (error) {
63
77
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return null;
64
- if (error instanceof SyntaxError) throw new Error("Hive CLI config is malformed. Run hive login again.");
65
78
  throw error;
66
79
  }
80
+ try {
81
+ // Checked on the open handle so the file cannot be swapped between check and read.
82
+ if (deps.platform !== "win32" && deps.uid !== undefined) assertPrivateConfigFile(file, await handle.stat(), deps.uid);
83
+ return assertStoredConfig(JSON.parse(await handle.readFile("utf8")));
84
+ } catch (error) {
85
+ if (error instanceof SyntaxError) throw new Error("Hive CLI config is malformed. Run hive3 login again.");
86
+ throw error;
87
+ } finally {
88
+ await handle.close();
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Write a private file (0600) into `directory` atomically. The directory is created
94
+ * with mode 0700 when it does not exist. The content is staged in a freshly created
95
+ * private temp directory (random name, 0700) so no predictable path is ever opened
96
+ * inside a possibly shared directory, then renamed over the destination. A symlink at
97
+ * the destination is replaced, never followed.
98
+ */
99
+ export async function writePrivateFile(directory, fileName, content) {
100
+ await fs.mkdir(directory, { mode: 0o700, recursive: true });
101
+ const staging = await fs.mkdtemp(path.join(directory, `.${fileName}.`));
102
+ try {
103
+ const staged = path.join(staging, fileName);
104
+ const handle = await fs.open(staged, "wx", 0o600);
105
+ try {
106
+ await handle.writeFile(content, "utf8");
107
+ await handle.chmod(0o600);
108
+ } finally {
109
+ await handle.close();
110
+ }
111
+ const destination = path.join(directory, fileName);
112
+ await fs.rename(staged, destination);
113
+ return destination;
114
+ } finally {
115
+ await fs.rm(staging, { force: true, recursive: true });
116
+ }
67
117
  }
68
118
 
69
119
  export async function saveCredential(credential, options, overrides = {}) {
70
120
  const deps = configDeps(overrides);
71
121
  const directory = configDirectory(deps.env, deps.platform, deps.homeDir);
72
- await fs.mkdir(directory, { mode: 0o700, recursive: true });
73
- const file = path.join(directory, "config.json");
74
122
  const body = {
75
123
  apiBaseUrl: options.apiBaseUrl,
76
124
  apiKey: credential.key,
@@ -78,10 +126,7 @@ export async function saveCredential(credential, options, overrides = {}) {
78
126
  keyPrefix: credential.keyPrefix,
79
127
  scopes: credential.scopes,
80
128
  };
81
- const tmp = `${file}.${process.pid}.tmp`;
82
- await fs.writeFile(tmp, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o600 });
83
- await fs.rename(tmp, file);
84
- return file;
129
+ return await writePrivateFile(directory, "config.json", `${JSON.stringify(body, null, 2)}\n`);
85
130
  }
86
131
 
87
132
  export async function clearConfig(overrides = {}) {
@@ -0,0 +1,18 @@
1
+ // @ts-check
2
+
3
+ export function createConversationsClient(client, community = false) {
4
+ const root = community ? "/community-messages" : "/conversations";
5
+ const thread = ref => `${root}/${encodeURIComponent(ref)}/messages`;
6
+ const message = (id, room) => community ? `${thread(room)}/${encodeURIComponent(id)}` : `${root}/messages/${encodeURIComponent(id)}`;
7
+ const write = (method, path, body, idempotencyKey) => client.request(method, path, { body: { ...body, confirmed: true }, idempotencyKey });
8
+ return {
9
+ list: query => client.request("GET", root, { query }),
10
+ read: (ref, query) => client.request("GET", thread(ref), { query }),
11
+ send: (ref, body, key) => write("POST", thread(ref), body, key),
12
+ edit: (id, content, key, room) => write("PATCH", message(id, room), { content }, key),
13
+ remove: (id, key, room) => write("DELETE", message(id, room), {}, key),
14
+ react: (id, emoji, present, key, room) => write("POST", `${message(id, room)}/reaction`, { emoji, present }, key),
15
+ markRead: (ref, key) => write("POST", `${root}/${encodeURIComponent(ref)}/read`, {}, key),
16
+ accept: (ref, key) => write("POST", `${root}/${encodeURIComponent(ref)}/accept`, {}, key),
17
+ };
18
+ }
@@ -0,0 +1,103 @@
1
+ // @ts-check
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import { readFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { authenticatedClient, parseBoolean, requiredFlagValue, writeJson, writeLine } from "./shared.js";
7
+ import { createConversationsClient } from "./conversations-client.js";
8
+
9
+ export function conversationsUsage() {
10
+ return `Usage:
11
+ hive3 conversations list [--requests] [--limit 1-100] [--cursor <cursor>]
12
+ hive3 conversations read <partner-account-id> [--limit 1-100] [--cursor <cursor>]
13
+ hive3 conversations send <partner-account-id> --content <text> --yes
14
+ hive3 conversations reply <partner-account-id> <message-id> --content <text> --yes
15
+ hive3 conversations edit <message-id> --content <text> --yes
16
+ hive3 conversations delete <message-id> --yes
17
+ hive3 conversations mark-read <partner-account-id> --yes
18
+ hive3 conversations accept <partner-account-id> --yes
19
+ hive3 conversations react <message-id> --emoji <emoji> --present true|false --yes
20
+ hive3 conversations community list [--limit 1-100] [--cursor <cursor>]
21
+ hive3 conversations community read <account> [--limit 1-100] [--cursor <cursor>]
22
+ hive3 conversations community send <account> --content <text> --yes
23
+ hive3 conversations community reply <account> <message-id> --content <text> --yes
24
+ hive3 conversations community edit <account> <message-id> --content <text> --yes
25
+ hive3 conversations community delete <account> <message-id> --yes
26
+ hive3 conversations community react <account> <message-id> --emoji <emoji> --present true|false --yes
27
+
28
+ Login needs separately approved --messages-access read|full; ordinary and Team access do not grant inbox access.
29
+ Send starts a DM if needed, subject to the app's membership and five-pending-message limit.
30
+ Use --content-file <path> instead of --content for send/reply/edit (1-4,000 characters).
31
+ All writes require --yes and support --idempotency-key <key> (otherwise generated); reuse the same key and payload after a lost response.
32
+ Reads are newest-first and return page.nextCursor; list --requests selects the message-request inbox.
33
+ Community list pages accepted memberships; pages may be empty after access/plan filtering, so follow nextCursor.
34
+ Writes are text-only; existing attachments remain readable. No attachment URLs, sender overrides, --account impersonation or staff inbox access.
35
+ Only your own messages may be edited/deleted. Reactions set a desired state, never toggle on retry.`;
36
+ }
37
+
38
+ export async function runConversationsCommand(args, deps) {
39
+ if (!args.length || args.some(arg => arg === "--help" || arg === "-h")) { writeLine(deps.stdout, conversationsUsage()); return 0; }
40
+ const community = args[0] === "community";
41
+ const [command, ...rest] = community ? args.slice(1) : args;
42
+ const reads = ["list", "read"];
43
+ const writes = ["send", "reply", "edit", "delete", "react", ...(community ? [] : ["mark-read", "accept"])];
44
+ if (![...reads, ...writes].includes(command)) throw new Error(`Unknown conversations command: ${command}`);
45
+ const writing = writes.includes(command);
46
+ let room;
47
+ let ref;
48
+ let replyToMessageId;
49
+ if (command !== "list") {
50
+ if (community) room = requiredFlagValue("community account", rest.shift());
51
+ if (!community || ["reply", "edit", "delete", "react"].includes(command)) ref = requiredFlagValue("account or message ID", rest.shift());
52
+ if (command === "reply") {
53
+ replyToMessageId = community ? ref : requiredFlagValue("reply message ID", rest.shift());
54
+ }
55
+ }
56
+ const allowed = writing ? ["--yes", "--idempotency-key"] : ["--limit", "--cursor"];
57
+ if (["send", "reply", "edit"].includes(command)) allowed.push("--content", "--content-file");
58
+ if (command === "react") allowed.push("--emoji", "--present");
59
+ if (!community && command === "list") allowed.push("--requests");
60
+ /** @type {Record<string, string | boolean>} */
61
+ const parsed = {};
62
+ for (let index = 0; index < rest.length; index++) {
63
+ const flag = rest[index];
64
+ if (!allowed.includes(flag)) throw new Error(`Unknown conversations option: ${flag}`);
65
+ if (parsed[flag] !== undefined) throw new Error(`${flag} may only be given once`);
66
+ parsed[flag] = flag === "--yes" || flag === "--requests" ? true : requiredFlagValue(flag, rest[++index]);
67
+ }
68
+ if (writing && !parsed["--yes"]) throw new Error(`conversations ${command} changes or sends a message. Pass --yes to confirm.`);
69
+ /** @type {{limit?: number, cursor?: string, requests?: boolean}} */
70
+ const query = {};
71
+ if (parsed["--limit"] !== undefined) {
72
+ const limit = Number(parsed["--limit"]);
73
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("--limit must be an integer between 1 and 100");
74
+ query.limit = limit;
75
+ }
76
+ if (typeof parsed["--cursor"] === "string") query.cursor = parsed["--cursor"];
77
+ if (parsed["--requests"]) query.requests = true;
78
+ let content;
79
+ if (["send", "reply", "edit"].includes(command)) {
80
+ if (parsed["--content"] !== undefined && parsed["--content-file"] !== undefined) throw new Error("Use either --content or --content-file");
81
+ const file = parsed["--content-file"];
82
+ content = typeof file === "string" ? await readFile(path.resolve(deps.cwd, file), "utf8") : parsed["--content"];
83
+ if (typeof content !== "string" || !content.trim() || Array.from(content.trim()).length > 4000) throw new Error("Message content must contain 1-4,000 characters");
84
+ }
85
+ const key = typeof parsed["--idempotency-key"] === "string" ? parsed["--idempotency-key"] : randomUUID();
86
+ if (!key.trim() || key.length > 128) throw new Error("--idempotency-key must contain 1-128 characters");
87
+ const emoji = parsed["--emoji"];
88
+ const present = parsed["--present"];
89
+ if (command === "react" && (typeof emoji !== "string" || typeof present !== "string")) throw new Error("Reactions require --emoji and --present true|false");
90
+ const desired = command === "react" ? parseBoolean(present, "--present") : undefined;
91
+ const client = createConversationsClient(await authenticatedClient(deps), community);
92
+ let result;
93
+ if (command === "list") result = await client.list(query);
94
+ else if (command === "read") result = await client.read(community ? room : ref, query);
95
+ else if (command === "send" || command === "reply") result = await client.send(community ? room : ref, { content, ...(replyToMessageId ? { replyToMessageId } : {}) }, key);
96
+ else if (command === "edit") result = await client.edit(ref, content, key, room);
97
+ else if (command === "delete") result = await client.remove(ref, key, room);
98
+ else if (command === "react") result = await client.react(ref, emoji, desired, key, room);
99
+ else if (command === "mark-read") result = await client.markRead(ref, key);
100
+ else result = await client.accept(ref, key);
101
+ writeJson(deps.stdout, result);
102
+ return 0;
103
+ }
@@ -1,44 +1,9 @@
1
1
  // @ts-check
2
2
 
3
- import { readFile } from "node:fs/promises";
4
-
5
- import { createApiClient, HiveApiError } from "./api-client.js";
6
- import { loadConfig } from "./config.js";
3
+ import { runAreaCommand } from "./area-commands.js";
4
+ import { authenticatedClient, parseBoolean, readJsonObject as readJsonFile, requiredFlagValue, writeJson } from "./shared.js";
7
5
  import { runUpdateCommand } from "./update.js";
8
6
 
9
- function writeLine(stream, message = "") {
10
- stream.write(`${message}\n`);
11
- }
12
-
13
- function writeJson(stream, value) {
14
- writeLine(stream, JSON.stringify(value, null, 2));
15
- }
16
-
17
- function requiredFlagValue(flag, value) {
18
- if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
19
- return value;
20
- }
21
-
22
- function parseBoolean(value, flag) {
23
- if (value === "true" || value === "1" || value === "yes") return true;
24
- if (value === "false" || value === "0" || value === "no") return false;
25
- throw new Error(`${flag} must be true or false`);
26
- }
27
-
28
- async function readJsonFile(file) {
29
- const parsed = JSON.parse(await readFile(file, "utf8"));
30
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
31
- throw new Error(`${file} must contain a JSON object`);
32
- }
33
- return parsed;
34
- }
35
-
36
- async function authenticatedClient(deps) {
37
- const config = await loadConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
38
- if (!config) throw new HiveApiError("Not logged in. Run hive login first.", { code: "auth_required", status: 401 });
39
- return createApiClient({ apiBaseUrl: config.apiBaseUrl, apiKey: config.apiKey, fetch: deps.fetch });
40
- }
41
-
42
7
  async function parseWorkflowPayload(args, allowedFlags = []) {
43
8
  const payload = {};
44
9
  for (let index = 0; index < args.length; index += 1) {
@@ -88,6 +53,11 @@ async function runNotifications(args, deps) {
88
53
  writeJson(deps.stdout, await client.listNotifications(parseNotificationListOptions(rest)));
89
54
  return;
90
55
  }
56
+ if (action === "unread-count") {
57
+ if (rest.length > 0) throw new Error(`Unknown notifications unread-count option: ${rest[0]}`);
58
+ writeJson(deps.stdout, await client.getUnreadNotificationCount());
59
+ return;
60
+ }
91
61
  if (action === "read") {
92
62
  const notificationId = requiredFlagValue("notification id", rest[0]);
93
63
  if (rest.length > 1) throw new Error(`Unknown notifications read option: ${rest[1]}`);
@@ -271,10 +241,10 @@ async function runCoursesWorkflow(args, deps) {
271
241
  }
272
242
  if (action === "approve" || action === "deny") {
273
243
  const courseId = requiredFlagValue("course id", rest[0]);
274
- const personId = requiredFlagValue("person id", rest[1]);
244
+ const accountId = requiredFlagValue("account id", rest[1]);
275
245
  if (rest.length > 2) throw new Error(`Unknown courses ${action} option: ${rest[2]}`);
276
246
  writeJson(deps.stdout, await client.workflowPatch(
277
- `courses/${encodeURIComponent(courseId)}/enrollments/${encodeURIComponent(personId)}`,
247
+ `courses/${encodeURIComponent(courseId)}/enrollments/${encodeURIComponent(accountId)}`,
278
248
  { accepted: action === "approve" },
279
249
  ));
280
250
  return true;
@@ -444,24 +414,24 @@ async function runCommunities(args, deps) {
444
414
  }
445
415
  if (action === "role") {
446
416
  const communityId = requiredFlagValue("community id", rest[0]);
447
- const personId = requiredFlagValue("person id", rest[1]);
417
+ const accountId = requiredFlagValue("account id", rest[1]);
448
418
  if (rest[2] !== "--role") throw new Error("--role is required");
449
419
  const role = requiredFlagValue("--role", rest[3]);
450
420
  if (role !== "admin" && role !== "moderator" && role !== "member") {
451
421
  throw new Error("--role must be admin, moderator, or member");
452
422
  }
453
423
  if (rest.length > 4) throw new Error(`Unknown communities role option: ${rest[4]}`);
454
- writeJson(deps.stdout, await client.setCommunityRole(communityId, personId, role));
424
+ writeJson(deps.stdout, await client.setCommunityRole(communityId, accountId, role));
455
425
  return;
456
426
  }
457
427
  if (action === "remove-member") {
458
428
  const communityId = requiredFlagValue("community id", rest[0]);
459
- const personId = requiredFlagValue("person id", rest[1]);
429
+ const accountId = requiredFlagValue("account id", rest[1]);
460
430
  if (rest[2] !== "--confirm") throw new Error("--confirm is required");
461
431
  const confirmation = requiredFlagValue("--confirm", rest[3]);
462
- if (confirmation !== personId) throw new Error("--confirm must exactly match the member person id");
432
+ if (confirmation !== accountId) throw new Error("--confirm must exactly match the member account id");
463
433
  if (rest.length > 4) throw new Error(`Unknown communities remove-member option: ${rest[4]}`);
464
- writeJson(deps.stdout, await client.removeCommunityMember(communityId, personId));
434
+ writeJson(deps.stdout, await client.removeCommunityMember(communityId, accountId));
465
435
  return;
466
436
  }
467
437
  if (action === "access") {
@@ -489,6 +459,7 @@ export async function runExtendedCommand(command, args, deps) {
489
459
  await runCommunities(args, deps);
490
460
  return true;
491
461
  }
462
+ if (await runAreaCommand(command, args, deps)) return true;
492
463
  if (command === "events") return await runEventsWorkflow(args, deps);
493
464
  if (command === "courses") return await runCoursesWorkflow(args, deps);
494
465
  if (command === "quests") return await runQuestsWorkflow(args, deps);
@@ -0,0 +1,15 @@
1
+ // @ts-check
2
+
3
+ export function createFeedbackClient(client, team = false) {
4
+ const root = team ? "/team/feedback" : "/feedback";
5
+ const ticket = ref => `${root}/${encodeURIComponent(ref)}`;
6
+ return {
7
+ list: query => client.request("GET", root, { query }),
8
+ get: ref => client.request("GET", ticket(ref)),
9
+ messages: (ref, query) => client.request("GET", `${ticket(ref)}/messages`, { query }),
10
+ reply: (ref, body, idempotencyKey) => client.request("POST", `${ticket(ref)}/messages`, { body: { body, confirmed: true }, idempotencyKey }),
11
+ status: (ref, status) => client.request("PATCH", `${ticket(ref)}/status`, { body: { status, confirmed: true } }),
12
+ uploadUrl: kind => client.request("POST", "/feedback/upload-url", { body: { kind } }),
13
+ submit: (body, idempotencyKey) => client.request("POST", "/feedback", { body: { ...body, confirmed: true }, idempotencyKey }),
14
+ };
15
+ }
@@ -0,0 +1,148 @@
1
+ // @ts-check
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import { readFile, stat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { authenticatedClient, postFileToUploadUrl, requiredFlagValue, writeJson, writeLine } from "./shared.js";
7
+ import { createFeedbackClient } from "./feedback-client.js";
8
+ import { createApiClient } from "./api-client.js";
9
+ import { loadConfig } from "./config.js";
10
+ import { feedbackReplay } from "./feedback-replay.js";
11
+
12
+ const MIME = {
13
+ ".gif": "image/gif", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp",
14
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
15
+ };
16
+
17
+ export function feedbackUsage() {
18
+ return `Usage:
19
+ hive3 feedback submit --kind bug|suggestion --description <text> [--description-file <path>] [--image <path>]... [--video <path>] --yes
20
+ hive3 feedback list [--limit 1-100] [--cursor <cursor>]
21
+ hive3 feedback get <ticket-id-or-HV-number>
22
+ hive3 feedback messages <ticket> [--limit 1-100] [--cursor <cursor>]
23
+ hive3 feedback reply <ticket> --body <text> [--body-file <path>] --yes
24
+ hive3 team feedback list [--status open|in_progress|resolved|closed] [--limit 1-100] [--cursor <cursor>]
25
+ hive3 team feedback get <ticket>
26
+ hive3 team feedback messages <ticket> [--limit 1-100] [--cursor <cursor>]
27
+ hive3 team feedback reply <ticket> --body <text> [--body-file <path>] --yes
28
+ hive3 team feedback status <ticket> --status open|in_progress|resolved|closed --yes
29
+
30
+ Submit/reply support --idempotency-key <key>; otherwise a fresh key is generated.
31
+ Attachment retries reuse private local upload references; keep the same key and original file contents.
32
+ Attachments: up to 4 images (8 MiB each), 1 video (19 MiB). Replies are text-only.
33
+ Feedback tickets are support conversations, not paid admission tickets.
34
+ Team commands require team scopes and current staff access.`;
35
+ }
36
+
37
+ function options(args, allowed) {
38
+ const result = { images: [], videos: [], yes: false };
39
+ for (let index = 0; index < args.length; index++) {
40
+ const flag = args[index];
41
+ if (flag === "--yes" && allowed.includes(flag)) { result.yes = true; continue; }
42
+ if (!allowed.includes(flag)) throw new Error(`Unknown feedback option: ${flag}`);
43
+ const value = requiredFlagValue(flag, args[++index]);
44
+ if (flag === "--image") result.images.push(value);
45
+ else if (flag === "--video") result.videos.push(value);
46
+ else {
47
+ const key = flag.slice(2);
48
+ if (result[key] !== undefined) throw new Error(`${flag} may only be given once`);
49
+ result[key] = value;
50
+ }
51
+ }
52
+ return result;
53
+ }
54
+ function queryOptions(parsed) {
55
+ const query = {};
56
+ if (parsed.limit !== undefined) {
57
+ const limit = Number(parsed.limit);
58
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("--limit must be an integer between 1 and 100");
59
+ query.limit = limit;
60
+ }
61
+ if (parsed.cursor !== undefined) query.cursor = parsed.cursor;
62
+ if (parsed.status !== undefined) {
63
+ if (!["open", "in_progress", "resolved", "closed"].includes(parsed.status)) throw new Error("Invalid feedback status");
64
+ query.status = parsed.status;
65
+ }
66
+ return query;
67
+ }
68
+ async function textOption(parsed, name, deps) {
69
+ if (parsed[name] !== undefined && parsed[`${name}-file`] !== undefined) throw new Error(`Use either --${name} or --${name}-file`);
70
+ const file = parsed[`${name}-file`];
71
+ const text = file ? await readFile(path.resolve(deps.cwd, file), "utf8") : parsed[name];
72
+ if (!text?.trim()) throw new Error(`--${name} or --${name}-file is required`);
73
+ return text;
74
+ }
75
+
76
+ export async function runFeedbackCommand(args, deps) {
77
+ if (args.some(arg => arg === "--help" || arg === "-h") || args.length === 0) {
78
+ writeLine(deps.stdout, feedbackUsage());
79
+ return 0;
80
+ }
81
+ const team = args[0] === "team";
82
+ const [command, ...rest] = team ? args.slice(1) : args;
83
+ if (!command) { writeLine(deps.stdout, feedbackUsage()); return 0; }
84
+ const mutations = ["submit", "reply", "status"];
85
+ if (!["list", "get", "messages", ...mutations].includes(command) || (team && command === "submit") || (!team && command === "status")) throw new Error(`Unknown feedback command: ${command}`);
86
+ const ref = ["get", "messages", "reply", "status"].includes(command) ? requiredFlagValue("ticket", rest.shift()) : undefined;
87
+ const allowed = command === "submit" ? ["--kind", "--description", "--description-file", "--image", "--video", "--yes", "--idempotency-key"]
88
+ : command === "reply" ? ["--body", "--body-file", "--yes", "--idempotency-key"]
89
+ : command === "status" ? ["--status", "--yes"]
90
+ : command === "list" ? ["--limit", "--cursor", ...(team ? ["--status"] : [])]
91
+ : command === "messages" ? ["--limit", "--cursor"] : [];
92
+ const parsed = options(rest, allowed);
93
+ if (mutations.includes(command) && !parsed.yes) throw new Error(`feedback ${command} sends or changes a support ticket. Pass --yes to confirm.`);
94
+ const query = queryOptions(parsed);
95
+ let description;
96
+ let body;
97
+ const files = [];
98
+ if (command === "submit") {
99
+ if (parsed.kind !== "bug" && parsed.kind !== "suggestion") throw new Error("--kind must be bug or suggestion");
100
+ description = await textOption(parsed, "description", deps);
101
+ if (description.trim().length < 10 || description.trim().length > 5000) throw new Error("Description must be between 10 and 5,000 characters");
102
+ if (parsed.images.length > 4 || parsed.videos.length > 1) throw new Error("Attach up to 4 images and 1 video");
103
+ /** @type {Array<["image" | "video", string[], number]>} */
104
+ const attachmentGroups = [["image", parsed.images, 8 * 1024 * 1024], ["video", parsed.videos, 19 * 1024 * 1024]];
105
+ for (const [kind, paths, maxBytes] of attachmentGroups) {
106
+ for (const file of paths) {
107
+ const filePath = path.resolve(deps.cwd, file);
108
+ const contentType = MIME[path.extname(filePath).toLowerCase()];
109
+ const info = await stat(filePath);
110
+ if (!contentType?.startsWith(`${kind}/`)) throw new Error(`Unsupported ${kind} file: ${file}`);
111
+ if (!info.isFile() || info.size < 1 || info.size > maxBytes) throw new Error(`Invalid ${kind} size: ${file}`);
112
+ const bytes = await readFile(filePath);
113
+ if (bytes.length < 1 || bytes.length > maxBytes) throw new Error(`Invalid ${kind} size: ${file}`);
114
+ files.push({ kind, filePath, contentType, bytes });
115
+ }
116
+ }
117
+ }
118
+ if (command === "reply") {
119
+ body = await textOption(parsed, "body", deps);
120
+ if (body.trim().length > 2000) throw new Error("Message must be between 1 and 2,000 characters");
121
+ }
122
+ if (command === "status" && !query.status) throw new Error("--status is required");
123
+ const idempotencyKey = parsed["idempotency-key"] ?? randomUUID();
124
+ if (!idempotencyKey.trim() || idempotencyKey.length > 128) throw new Error("--idempotency-key must contain 1-128 characters");
125
+ const config = command === "submit" ? await loadConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform }) : null;
126
+ if (command === "submit" && !config) throw new Error("Not logged in. Run hive3 login first.");
127
+ const client = config ? createApiClient({ apiBaseUrl: config.apiBaseUrl, apiKey: config.apiKey, fetch: deps.fetch }) : await authenticatedClient(deps);
128
+ const feedback = createFeedbackClient(client, team);
129
+ let result;
130
+ if (command === "list") result = await feedback.list(query);
131
+ else if (command === "get") result = await feedback.get(ref);
132
+ else if (command === "messages") result = await feedback.messages(ref, query);
133
+ else if (command === "reply") result = await feedback.reply(ref, body, idempotencyKey);
134
+ else if (command === "status") result = await feedback.status(ref, query.status);
135
+ else {
136
+ const replay = await feedbackReplay(deps, config, idempotencyKey, { kind: parsed.kind, description }, files);
137
+ const attachments = replay.attachments;
138
+ for (const file of files.slice(attachments.length)) {
139
+ const issued = await feedback.uploadUrl(file.kind);
140
+ const uploaded = await postFileToUploadUrl(client, deps, issued.data.uploadUrl, file.filePath, file.contentType, file.bytes);
141
+ if (!uploaded.ok || typeof uploaded.parsed.storageId !== "string") throw new Error(`Feedback attachment upload failed (${uploaded.status}): ${uploaded.parsed.error ?? "missing storageId"}`);
142
+ await replay.append({ kind: file.kind, storageId: uploaded.parsed.storageId });
143
+ }
144
+ result = await feedback.submit({ kind: parsed.kind, description, attachments }, idempotencyKey);
145
+ }
146
+ writeJson(deps.stdout, result);
147
+ return 0;
148
+ }
@@ -0,0 +1,43 @@
1
+ // @ts-check
2
+
3
+ import { createHash } from "node:crypto";
4
+ import { lstat, readFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { configDirectory, writePrivateFile } from "./config.js";
7
+
8
+ /** Preserve upload references across dropped submission responses without retaining credentials or report text. */
9
+ export async function feedbackReplay(deps, config, idempotencyKey, payload, files) {
10
+ const binding = createHash("sha256").update(JSON.stringify([config.apiBaseUrl, config.apiKey])).digest("hex");
11
+ const fileName = `${createHash("sha256").update(JSON.stringify([binding, idempotencyKey])).digest("hex")}.json`;
12
+ const directory = path.join(configDirectory(deps.env, deps.platform, deps.homeDir), "feedback-requests");
13
+ const fingerprint = createHash("sha256").update(JSON.stringify({
14
+ kind: payload.kind, description: payload.description.trim(),
15
+ files: files.map(file => ({ kind: file.kind, contentType: file.contentType, sha256: createHash("sha256").update(file.bytes).digest("hex") })),
16
+ })).digest("hex");
17
+ let manifest = { binding, fingerprint, attachments: [] };
18
+ try {
19
+ const directoryInfo = await lstat(directory);
20
+ if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) throw new Error("Refusing unsafe feedback replay directory");
21
+ const file = path.join(directory, fileName);
22
+ const info = await lstat(file);
23
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("Refusing unsafe feedback replay manifest");
24
+ const stored = JSON.parse(await readFile(file, "utf8"));
25
+ if (stored.binding !== binding || stored.fingerprint !== fingerprint) throw new Error("Idempotency key was already used for different feedback. Use the original payload or a new key.");
26
+ if (!Array.isArray(stored.attachments) || stored.attachments.length > files.length
27
+ || stored.attachments.some((item, index) => !item || item.kind !== files[index].kind || typeof item.storageId !== "string" || !item.storageId)) {
28
+ throw new Error("Feedback replay manifest is invalid. Refusing to reupload attachments for this key.");
29
+ }
30
+ manifest = stored;
31
+ } catch (error) {
32
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") throw error;
33
+ await writePrivateFile(directory, fileName, JSON.stringify(manifest));
34
+ }
35
+ return {
36
+ attachments: manifest.attachments,
37
+ async append(attachment) {
38
+ manifest.attachments.push(attachment);
39
+ // Persist each upload before submission, so both partial uploads and lost POST responses can resume.
40
+ await writePrivateFile(directory, fileName, JSON.stringify(manifest));
41
+ },
42
+ };
43
+ }