@hive3/cli 0.3.0 → 0.4.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/commands.js CHANGED
@@ -7,10 +7,17 @@ import { createApiClient, HiveApiError, isResourceKind } from "./api-client.js";
7
7
  import { clearConfig, loadConfig } from "./config.js";
8
8
  import { runExtendedCommand } from "./extended-commands.js";
9
9
  import { login, loginUsage, parseLoginArgs } from "./login.js";
10
- import { resourceUsage, usage } from "./usage.js";
10
+ import { runSkill } from "./skill.js";
11
+ import { authenticatedClient, parseBoolean, postFileToUploadUrl, requiredFlagValue, writeJson, writeLine } from "./shared.js";
12
+ import { CURRENT_VERSION, updateUsage } from "./update.js";
13
+ import { commandUsage, resourceUsage, usage } from "./usage.js";
14
+
15
+ // Commands that run with no arguments.
16
+ const SIMPLE_COMMANDS = new Set(["login", "logout", "update", "whoami", "capabilities"]);
11
17
 
12
18
  function defaultDeps(overrides = {}) {
13
19
  return {
20
+ cwd: process.cwd(),
14
21
  env: process.env,
15
22
  fetch: globalThis.fetch,
16
23
  homeDir: undefined,
@@ -38,19 +45,6 @@ function loginDeps(deps) {
38
45
  return next;
39
46
  }
40
47
 
41
- function writeLine(stream, message = "") {
42
- stream.write(`${message}\n`);
43
- }
44
-
45
- function writeJson(stream, value) {
46
- writeLine(stream, JSON.stringify(value, null, 2));
47
- }
48
-
49
- function requiredFlagValue(flag, value) {
50
- if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
51
- return value;
52
- }
53
-
54
48
  function takeAccountFlag(args) {
55
49
  let account;
56
50
  const rest = [];
@@ -152,12 +146,6 @@ async function parseResourcePayload(args, includeOwner) {
152
146
  if (Object.keys(payload).length === 0) throw new Error("At least one resource field is required");
153
147
  return { idempotencyKey, payload };
154
148
  }
155
- function parseBoolean(value, flag) {
156
- if (value === "true" || value === "1" || value === "yes") return true;
157
- if (value === "false" || value === "0" || value === "no") return false;
158
- throw new Error(`${flag} must be true or false`);
159
- }
160
-
161
149
  function parseCsv(value) {
162
150
  return value.split(",").map((item) => item.trim()).filter(Boolean);
163
151
  }
@@ -234,12 +222,6 @@ function mimeFromPath(filePath) {
234
222
  }[ext] || "";
235
223
  }
236
224
 
237
- async function authenticatedClient(deps) {
238
- const config = await loadConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
239
- if (!config) throw new HiveApiError("Not logged in. Run hive login first.", { code: "auth_required", status: 401 });
240
- return createApiClient({ apiBaseUrl: config.apiBaseUrl, apiKey: config.apiKey, fetch: deps.fetch });
241
- }
242
-
243
225
  function capabilityLabels(capabilities) {
244
226
  return Object.entries(capabilities)
245
227
  .filter(([, enabled]) => enabled)
@@ -250,10 +232,10 @@ async function runWhoami(deps) {
250
232
  const result = await (await authenticatedClient(deps)).whoami();
251
233
  const data = result.data;
252
234
  const person = data.person;
253
- writeLine(deps.stdout, `Person: ${person.displayName || person.handle || person.id}`);
235
+ writeLine(deps.stdout, `Account: ${person.displayName || person.handle || person.id}`);
254
236
  if (person.handle) writeLine(deps.stdout, `Handle: @${person.handle}`);
255
237
  writeLine(deps.stdout, `Scopes: ${data.credential.scopes.join(", ") || "none"}`);
256
- writeLine(deps.stdout, `Community targets: ${data.communities.length}`);
238
+ writeLine(deps.stdout, `Accounts this key can act on: ${data.communities.length}`);
257
239
  for (const community of data.communities) {
258
240
  writeLine(deps.stdout, `- ${community.name} (${community.role}): ${capabilityLabels(community.capabilities).join(", ")}`);
259
241
  }
@@ -263,7 +245,7 @@ async function runCapabilities(deps) {
263
245
  const result = await (await authenticatedClient(deps)).capabilities();
264
246
  const communities = result.data.communities;
265
247
  if (communities.length === 0) {
266
- writeLine(deps.stdout, "No admin or moderator community targets are available.");
248
+ writeLine(deps.stdout, "No accounts are available to this key.");
267
249
  return;
268
250
  }
269
251
  for (const community of communities) {
@@ -300,6 +282,12 @@ async function runResource(kind, args, deps) {
300
282
  writeJson(deps.stdout, await client.archiveResource(kind, id));
301
283
  return;
302
284
  }
285
+ if (action === "get") {
286
+ const id = requiredFlagValue("resource id", rest[0]);
287
+ if (rest.length > 1) throw new Error(`Unknown ${kind} get option: ${rest[1]}`);
288
+ writeJson(deps.stdout, await client.getResource(kind, id));
289
+ return;
290
+ }
303
291
  throw new Error(`Unknown ${kind} action: ${action}`);
304
292
  }
305
293
 
@@ -390,17 +378,11 @@ async function runUpload(args, deps) {
390
378
  const client = await authenticatedClient(deps);
391
379
  const issued = await client.createUploadUrl({ byteSize: fileStat.size, contentType, fileName, purpose });
392
380
  const { uploadUrl, ...issuedSafe } = issued.data;
393
- const bytes = await readFile(filePath);
394
- const response = await deps.fetch(uploadUrl, {
395
- body: new Blob([bytes], { type: contentType }),
396
- headers: { "Content-Type": contentType },
397
- method: "POST",
398
- });
399
- const text = await response.text();
400
- const parsed = text ? JSON.parse(text) : {};
401
- if (!response.ok) {
402
- throw new HiveApiError(`Upload failed with status ${response.status}`, { code: "upload_failed", status: response.status });
381
+ const upload = await postFileToUploadUrl(client, deps, uploadUrl, filePath, contentType);
382
+ if (!upload.ok) {
383
+ throw new HiveApiError(`Upload failed with status ${upload.status}`, { code: "upload_failed", status: upload.status });
403
384
  }
385
+ const parsed = upload.parsed;
404
386
  writeJson(deps.stdout, { data: { ...issuedSafe, ...parsed } });
405
387
  }
406
388
 
@@ -440,12 +422,27 @@ async function runAccount(args, deps) {
440
422
  return;
441
423
  }
442
424
  if (deletionAction === "request") {
443
- if (rest[1] !== "--confirm") throw new Error("--confirm DELETE is required");
444
- const confirmation = requiredFlagValue("--confirm", rest[2]);
445
- if (rest.length > 3) throw new Error(`Unknown account deletion request option: ${rest[3]}`);
446
- writeJson(deps.stdout, await client.requestAccountDeletion(confirmation));
425
+ throw new Error("Account deletion can't be requested from the CLI. Delete your account in the Hive app under Settings.");
426
+ }
427
+ throw new Error(`Unknown account deletion action: ${deletionAction || ""}`.trim());
428
+ }
429
+ if (action === "linked-communities") {
430
+ const linkedAction = rest[0] ?? "list";
431
+ if (linkedAction === "list") {
432
+ if (rest.length > 1) throw new Error(`Unknown account linked-communities list option: ${rest[1]}`);
433
+ writeJson(deps.stdout, await client.listLinkedCommunities());
447
434
  return;
448
435
  }
436
+ if (linkedAction === "disconnect") {
437
+ const communityId = requiredFlagValue("community id", rest[1]);
438
+ if (rest[2] !== "--confirm" || rest[3] !== communityId) {
439
+ throw new Error("--confirm must exactly match the community id");
440
+ }
441
+ if (rest.length > 4) throw new Error(`Unknown account linked-communities disconnect option: ${rest[4]}`);
442
+ writeJson(deps.stdout, await client.disconnectLinkedCommunity(communityId));
443
+ return;
444
+ }
445
+ throw new Error(`Unknown account linked-communities action: ${linkedAction}`);
449
446
  }
450
447
  throw new Error(`Unknown account action: ${action || ""}`.trim());
451
448
  }
@@ -497,6 +494,12 @@ function renderError(error) {
497
494
  if (error instanceof HiveApiError) {
498
495
  const scopeText = error.requiredScopes.length > 0 ? ` Required scopes: ${error.requiredScopes.join(", ")}.` : "";
499
496
  if (error.code === "auth_required") return error.message;
497
+ if (error.code === "plan_required") {
498
+ return [
499
+ "Your Hive plan doesn't include API access: the API and CLI need Honey Bee or above.",
500
+ "Upgrade under Settings in the Hive app. This key works again once the plan is active; you don't need to log in again.",
501
+ ].join(" ");
502
+ }
500
503
  return `Hive API error ${error.status} (${error.code}): ${error.message}.${scopeText}`;
501
504
  }
502
505
  return error instanceof Error ? error.message : "Hive CLI failed.";
@@ -510,6 +513,22 @@ export async function main(argv, overrides = {}) {
510
513
  writeLine(deps.stdout, usage());
511
514
  return 0;
512
515
  }
516
+ if (command === "--version" || command === "-v") {
517
+ if (rest.length > 0) throw new Error(`Unknown option: ${rest[0]}`);
518
+ writeLine(deps.stdout, CURRENT_VERSION);
519
+ return 0;
520
+ }
521
+ // --help/-h anywhere after a command prints that command's help and never executes it.
522
+ const wantsHelp = rest.some((argument) => argument === "--help" || argument === "-h");
523
+ const helpText = command === "login"
524
+ ? loginUsage()
525
+ : command === "update"
526
+ ? updateUsage()
527
+ : isResourceKind(command) ? resourceUsage(command) : commandUsage(command);
528
+ if (helpText && (wantsHelp || (rest.length === 0 && command !== "upload" && !SIMPLE_COMMANDS.has(command)))) {
529
+ writeLine(deps.stdout, helpText);
530
+ return 0;
531
+ }
513
532
  if (command === "login") {
514
533
  const parsed = parseLoginArgs(rest, deps.env);
515
534
  if (parsed.help) writeLine(deps.stdout, loginUsage());
@@ -530,13 +549,17 @@ export async function main(argv, overrides = {}) {
530
549
  } catch {
531
550
  writeLine(
532
551
  deps.stderr,
533
- "Warning: could not revoke the server credential. Revoke it at Settings → Developer credentials.",
552
+ "Warning: could not revoke the server credential. Revoke it at Settings → Help & feedback → Developer API keys (https://app.hive3.tech/settings/api-keys).",
534
553
  );
535
554
  }
536
555
  const file = await clearConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
537
556
  writeLine(deps.stdout, `Removed Hive CLI credential at ${file}.`);
538
557
  return 0;
539
558
  }
559
+ if (command === "skill") {
560
+ await runSkill(rest, deps);
561
+ return 0;
562
+ }
540
563
  if (command === "whoami") {
541
564
  if (rest.length > 0) throw new Error(`Unknown whoami option: ${rest[0]}`);
542
565
  await runWhoami(deps);
package/src/config.js CHANGED
@@ -38,11 +38,11 @@ function configDeps(overrides = {}) {
38
38
 
39
39
  function assertStoredConfig(value) {
40
40
  if (!value || typeof value !== "object" || Array.isArray(value)) {
41
- throw new Error("Hive CLI config is invalid. Run hive login again.");
41
+ throw new Error("Hive CLI config is invalid. Run hive3 login again.");
42
42
  }
43
43
  const record = /** @type {Record<string, unknown>} */ (value);
44
44
  if (typeof record.apiBaseUrl !== "string" || typeof record.apiKey !== "string") {
45
- throw new Error("Hive CLI config is missing credentials. Run hive login again.");
45
+ throw new Error("Hive CLI config is missing credentials. Run hive3 login again.");
46
46
  }
47
47
  return /** @type {StoredHiveConfig} */ ({
48
48
  apiBaseUrl: record.apiBaseUrl,
@@ -61,16 +61,41 @@ export async function loadConfig(overrides = {}) {
61
61
  return assertStoredConfig(JSON.parse(text));
62
62
  } catch (error) {
63
63
  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.");
64
+ if (error instanceof SyntaxError) throw new Error("Hive CLI config is malformed. Run hive3 login again.");
65
65
  throw error;
66
66
  }
67
67
  }
68
68
 
69
+ /**
70
+ * Write a private file (0600) into `directory` atomically. The directory is created
71
+ * with mode 0700 when it does not exist. The content is staged in a freshly created
72
+ * private temp directory (random name, 0700) so no predictable path is ever opened
73
+ * inside a possibly shared directory, then renamed over the destination. A symlink at
74
+ * the destination is replaced, never followed.
75
+ */
76
+ export async function writePrivateFile(directory, fileName, content) {
77
+ await fs.mkdir(directory, { mode: 0o700, recursive: true });
78
+ const staging = await fs.mkdtemp(path.join(directory, `.${fileName}.`));
79
+ try {
80
+ const staged = path.join(staging, fileName);
81
+ const handle = await fs.open(staged, "wx", 0o600);
82
+ try {
83
+ await handle.writeFile(content, "utf8");
84
+ await handle.chmod(0o600);
85
+ } finally {
86
+ await handle.close();
87
+ }
88
+ const destination = path.join(directory, fileName);
89
+ await fs.rename(staged, destination);
90
+ return destination;
91
+ } finally {
92
+ await fs.rm(staging, { force: true, recursive: true });
93
+ }
94
+ }
95
+
69
96
  export async function saveCredential(credential, options, overrides = {}) {
70
97
  const deps = configDeps(overrides);
71
98
  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
99
  const body = {
75
100
  apiBaseUrl: options.apiBaseUrl,
76
101
  apiKey: credential.key,
@@ -78,10 +103,7 @@ export async function saveCredential(credential, options, overrides = {}) {
78
103
  keyPrefix: credential.keyPrefix,
79
104
  scopes: credential.scopes,
80
105
  };
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;
106
+ return await writePrivateFile(directory, "config.json", `${JSON.stringify(body, null, 2)}\n`);
85
107
  }
86
108
 
87
109
  export async function clearConfig(overrides = {}) {
@@ -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);
package/src/login.js CHANGED
@@ -13,17 +13,22 @@ export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
13
13
 
14
14
  export function loginUsage() {
15
15
  return [
16
- "Usage: hive login [options]",
16
+ "Usage: hive3 login [options]",
17
+ "",
18
+ "Opens an approval page in your browser; approve only the code shown in this terminal.",
19
+ "Creating a CLI key needs a Honey Bee plan or above.",
17
20
  "",
18
21
  "Options:",
19
22
  " --access <read|full> Permission bundle to approve; omit to choose in browser",
20
- " --api-url <url> Public API base URL",
21
- " --app-url <url> Browser app URL for approval",
22
- " --label <label> Local credential label",
23
+ " --api-url <url> Public API base URL (default $HIVE_API_URL, then https://app.hive3.tech/api/v1)",
24
+ " --app-url <url> Browser app URL for approval (default $HIVE_APP_URL, then https://app.hive3.tech)",
25
+ " --label <label> Name shown on the approval page",
23
26
  " --scope <scope> Advanced: request an exact API scope, repeatable",
24
27
  " --timeout-ms <ms> Login polling timeout",
25
28
  " --no-open Print the URL without opening a browser",
26
29
  " -h, --help Show help",
30
+ "",
31
+ "HIVE_API_URL and HIVE_APP_URL only apply to this login. Later commands use the API URL stored with the key.",
27
32
  ].join("\n");
28
33
  }
29
34
 
@@ -185,8 +190,8 @@ export async function login(options, overrides = {}) {
185
190
  return { configPath, keyPrefix: result.credential.keyPrefix, status: "approved" };
186
191
  }
187
192
  if (result.status === "denied") throw new Error("Hive CLI login was denied in the browser.");
188
- if (result.status === "expired") throw new Error("Hive CLI login expired. Run hive login again.");
189
- if (result.status === "completed") throw new Error("Hive CLI login was already completed. Run hive login again.");
193
+ if (result.status === "expired") throw new Error("Hive CLI login expired. Run hive3 login again.");
194
+ if (result.status === "completed") throw new Error("Hive CLI login was already completed. Run hive3 login again.");
190
195
  if (result.status === "not_found") throw new Error("Hive CLI login request was not found.");
191
196
  await deps.sleep(pollIntervalMs);
192
197
  }
package/src/shared.js ADDED
@@ -0,0 +1,86 @@
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
+ export function writeLine(stream, message = "") {
9
+ stream.write(`${message}\n`);
10
+ }
11
+
12
+ export function writeJson(stream, value) {
13
+ writeLine(stream, JSON.stringify(value, null, 2));
14
+ }
15
+
16
+ export function requiredFlagValue(flag, value) {
17
+ if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
18
+ return value;
19
+ }
20
+
21
+ export 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
+ export async function readJsonObject(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
+ export 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 hive3 login first.", { code: "auth_required", status: 401 });
38
+ return createApiClient({ apiBaseUrl: config.apiBaseUrl, apiKey: config.apiKey, fetch: deps.fetch });
39
+ }
40
+
41
+ const UPLOAD_PATH = "/internal/storage/upload";
42
+ const loopbackHosts = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
43
+
44
+ /**
45
+ * Refuse any server-returned upload URL that is not an https (loopback-only http)
46
+ * Hive storage endpoint. The API issues `<CONVEX_SITE_URL>/internal/storage/upload?token=...`,
47
+ * so the host must be the API host itself or a Convex site/cloud host.
48
+ * @param {string} uploadUrl
49
+ * @param {string} apiBaseUrl
50
+ */
51
+ export function assertTrustedUploadUrl(uploadUrl, apiBaseUrl) {
52
+ let target;
53
+ try {
54
+ target = new URL(uploadUrl);
55
+ } catch {
56
+ throw new Error("Refusing to upload: the server returned an invalid upload URL.");
57
+ }
58
+ const api = new URL(apiBaseUrl);
59
+ const loopback = loopbackHosts.has(target.hostname);
60
+ const secure = target.protocol === "https:" || (target.protocol === "http:" && loopback && loopbackHosts.has(api.hostname));
61
+ const trustedHost = target.hostname === api.hostname
62
+ || target.hostname.endsWith(".convex.site")
63
+ || target.hostname.endsWith(".convex.cloud")
64
+ || (loopback && loopbackHosts.has(api.hostname));
65
+ if (!secure || !trustedHost || target.username || target.password || target.pathname !== UPLOAD_PATH) {
66
+ throw new Error(
67
+ `Refusing to upload: the server returned an upload URL that is not an https Hive storage endpoint (${target.protocol}//${target.host}).`,
68
+ );
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Validate the issued upload URL, then POST the file bytes to it (no Hive credentials are sent).
74
+ * @returns {Promise<{ ok: boolean, parsed: any, status: number }>}
75
+ */
76
+ export async function postFileToUploadUrl(client, deps, uploadUrl, filePath, contentType) {
77
+ assertTrustedUploadUrl(uploadUrl, client.apiBaseUrl);
78
+ const response = await deps.fetch(uploadUrl, {
79
+ body: new Blob([await readFile(filePath)], { type: contentType }),
80
+ headers: { "Content-Type": contentType },
81
+ method: "POST",
82
+ redirect: "error",
83
+ });
84
+ const text = await response.text();
85
+ return { ok: response.ok, parsed: text ? JSON.parse(text) : {}, status: response.status };
86
+ }