@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/login.js CHANGED
@@ -4,26 +4,39 @@ import { spawn } from "node:child_process";
4
4
 
5
5
  import { HiveApiError, normalizeBaseUrl, postJson } from "./api-client.js";
6
6
  import { saveCredential } from "./config.js";
7
+ import { terminalText, writeLine } from "./shared.js";
7
8
 
8
9
  export const DEFAULT_API_BASE_URL = "https://app.hive3.tech/api/v1";
9
10
  export const DEFAULT_APP_URL = "https://app.hive3.tech";
10
11
  export const DEFAULT_LABEL = "Hive CLI";
11
12
  export const DEFAULT_PERMISSION_MODE = "select";
12
13
  export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
14
+ // Login only talks to these hosts (https) or to loopback for local development unless
15
+ // --allow-custom-api-url is given: whichever server answers receives the new API key.
16
+ const KNOWN_HIVE3_HOSTS = new Set(["app.hive3.tech", "staging.hive3.tech"]);
17
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
13
18
 
14
19
  export function loginUsage() {
15
20
  return [
16
- "Usage: hive login [options]",
21
+ "Usage: hive3 login [options]",
22
+ "",
23
+ "Opens an approval page in your browser; approve only the code shown in this terminal.",
24
+ "Creating a CLI key needs Honey Bee or above, or current Team access.",
17
25
  "",
18
26
  "Options:",
19
27
  " --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",
28
+ " --messages-access <read|full> Separately request private conversations and messaging",
29
+ " --api-url <url> Public API base URL (default $HIVE_API_URL, then https://app.hive3.tech/api/v1)",
30
+ " --app-url <url> Browser app URL for approval (default $HIVE_APP_URL, then the API URL's origin)",
31
+ " --allow-custom-api-url Allow API/app hosts other than app.hive3.tech, staging.hive3.tech or localhost",
32
+ " --label <label> Name shown on the approval page",
23
33
  " --scope <scope> Advanced: request an exact API scope, repeatable",
24
34
  " --timeout-ms <ms> Login polling timeout",
25
35
  " --no-open Print the URL without opening a browser",
26
36
  " -h, --help Show help",
37
+ "",
38
+ "HIVE_API_URL and HIVE_APP_URL only apply to this login. Later commands use the API URL stored with the key.",
39
+ "Only pass --api-url, --app-url or --allow-custom-api-url for a server you run or trust: it receives your new key.",
27
40
  ].join("\n");
28
41
  }
29
42
 
@@ -34,13 +47,15 @@ function requiredFlagValue(flag, value) {
34
47
 
35
48
  export function parseLoginArgs(args, env = process.env) {
36
49
  const options = {
50
+ allowCustomApiUrl: false,
37
51
  apiBaseUrl: env.HIVE_API_URL || DEFAULT_API_BASE_URL,
38
- appUrl: env.HIVE_APP_URL || DEFAULT_APP_URL,
52
+ appUrl: env.HIVE_APP_URL || "",
39
53
  label: DEFAULT_LABEL,
40
54
  noOpen: false,
41
55
  permissionMode: DEFAULT_PERMISSION_MODE,
42
56
  permissionModeExplicit: false,
43
57
  scopes: [],
58
+ messagesAccess: undefined,
44
59
  timeoutMs: DEFAULT_TIMEOUT_MS,
45
60
  };
46
61
 
@@ -48,12 +63,20 @@ export function parseLoginArgs(args, env = process.env) {
48
63
  const flag = args[index];
49
64
  if (flag === "--no-open") {
50
65
  options.noOpen = true;
66
+ } else if (flag === "--allow-custom-api-url") {
67
+ options.allowCustomApiUrl = true;
51
68
  } else if (flag === "--access" || flag === "--permission") {
52
69
  index += 1;
53
70
  const value = requiredFlagValue(flag, args[index]);
54
71
  if (value !== "read" && value !== "full") throw new Error(`${flag} must be read or full`);
55
72
  options.permissionMode = value;
56
73
  options.permissionModeExplicit = true;
74
+ } else if (flag === "--messages-access") {
75
+ index += 1;
76
+ const value = requiredFlagValue(flag, args[index]);
77
+ if (value !== "read" && value !== "full") throw new Error("--messages-access must be read or full");
78
+ if (options.messagesAccess !== undefined) throw new Error("--messages-access may only be given once");
79
+ options.messagesAccess = value;
57
80
  } else if (flag === "--api-url") {
58
81
  index += 1;
59
82
  options.apiBaseUrl = requiredFlagValue(flag, args[index]);
@@ -82,9 +105,60 @@ export function parseLoginArgs(args, env = process.env) {
82
105
  if (options.permissionModeExplicit && options.scopes.length > 0) {
83
106
  throw new Error("--access cannot be combined with --scope. Use one permission bundle or exact scopes.");
84
107
  }
108
+ if (!options.appUrl) options.appUrl = defaultAppUrl(options.apiBaseUrl);
85
109
  return { help: false, options };
86
110
  }
87
111
 
112
+ function defaultAppUrl(apiBaseUrl) {
113
+ try {
114
+ return new URL(apiBaseUrl).origin;
115
+ } catch {
116
+ return DEFAULT_APP_URL;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Refuse API/app hosts outside the Hive3 allowlist unless the user explicitly opted in,
122
+ * in which case every custom host is named in a warning before anything is sent.
123
+ * @returns {string[]} custom hostnames the user opted into
124
+ */
125
+ export function assertTrustedLoginHosts(options) {
126
+ const custom = [];
127
+ for (const [flag, url] of [["--api-url", options.apiBaseUrl], ["--app-url", options.appUrl]]) {
128
+ let parsed;
129
+ try {
130
+ parsed = new URL(url);
131
+ } catch {
132
+ throw new Error(`Invalid ${flag} value. Provide an absolute URL such as ${DEFAULT_APP_URL}.`);
133
+ }
134
+ const known = (parsed.protocol === "https:" && KNOWN_HIVE3_HOSTS.has(parsed.hostname)) || LOOPBACK_HOSTS.has(parsed.hostname);
135
+ if (known || custom.includes(parsed.hostname)) continue;
136
+ if (!options.allowCustomApiUrl) {
137
+ throw new Error(
138
+ `Refusing to log in: ${parsed.host} (${flag} or its HIVE_* environment variable) is not a Hive3 host. `
139
+ + "That server would receive your new API key. Pass --allow-custom-api-url only if you set this URL yourself and trust the server.",
140
+ );
141
+ }
142
+ custom.push(parsed.hostname);
143
+ }
144
+ return custom;
145
+ }
146
+
147
+ /** The approval URL is opened and shown to the user, so it must stay on the expected app origin. */
148
+ export function assertApprovalUrl(approvalUrl, appUrl) {
149
+ const expectedOrigin = new URL(appUrl).origin;
150
+ let parsed;
151
+ try {
152
+ parsed = new URL(String(approvalUrl));
153
+ } catch {
154
+ parsed = undefined;
155
+ }
156
+ if (!parsed || parsed.origin !== expectedOrigin || parsed.username || parsed.password || !isSafeBrowserUrl(parsed.toString())) {
157
+ throw new Error(`Refusing to continue: the server returned an approval URL outside ${expectedOrigin}. Do not approve any code from this login.`);
158
+ }
159
+ return parsed.toString();
160
+ }
161
+
88
162
  export function isSafeBrowserUrl(url) {
89
163
  let parsed;
90
164
  try {
@@ -125,19 +199,20 @@ function defaultDeps() {
125
199
  openBrowser,
126
200
  platform: process.platform,
127
201
  sleep,
202
+ stderr: process.stderr,
128
203
  stdout: process.stdout,
129
204
  };
130
205
  }
131
206
 
132
- function writeLine(stream, message = "") {
133
- stream.write(`${message}\n`);
134
- }
135
-
136
207
  export async function login(options, overrides = {}) {
137
208
  const deps = { ...defaultDeps(), ...overrides };
138
209
  const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl);
210
+ const appUrl = options.appUrl || defaultAppUrl(apiBaseUrl);
211
+ for (const host of assertTrustedLoginHosts({ ...options, apiBaseUrl, appUrl })) {
212
+ writeLine(deps.stderr, terminalText(`Warning: logging in through custom host ${host}, not a Hive3 server. It will receive your new API key.`));
213
+ }
139
214
  const payload = {
140
- appUrl: options.appUrl,
215
+ appUrl,
141
216
  label: options.label,
142
217
  };
143
218
  if (options.scopes.length > 0) {
@@ -145,6 +220,7 @@ export async function login(options, overrides = {}) {
145
220
  } else {
146
221
  payload.permissionMode = options.permissionMode || DEFAULT_PERMISSION_MODE;
147
222
  }
223
+ if (options.messagesAccess !== undefined) payload.messagesAccess = options.messagesAccess;
148
224
  const start = await postJson(deps.fetch, `${apiBaseUrl}/cli/auth/start`, payload);
149
225
  const data = start.data;
150
226
  // A malformed server response must not turn the poll loop into a busy loop
@@ -152,9 +228,10 @@ export async function login(options, overrides = {}) {
152
228
  const rawPollIntervalMs = Number(data.pollIntervalMs);
153
229
  const pollIntervalMs = Number.isFinite(rawPollIntervalMs) && rawPollIntervalMs >= 500 ? rawPollIntervalMs : 2000;
154
230
 
155
- writeLine(deps.stdout, `Open this URL to approve Hive CLI access: ${data.approvalUrl}`);
156
- writeLine(deps.stdout, `Code: ${data.code} (type it on the approval page)`);
157
- if (!options.noOpen) deps.openBrowser(data.approvalUrl, deps.platform);
231
+ const approvalUrl = assertApprovalUrl(data.approvalUrl, appUrl);
232
+ writeLine(deps.stdout, `Open this URL to approve Hive CLI access: ${approvalUrl}`);
233
+ writeLine(deps.stdout, terminalText(`Code: ${data.code} (type it on the approval page)`));
234
+ if (!options.noOpen) deps.openBrowser(approvalUrl, deps.platform);
158
235
 
159
236
  const deadline = deps.now() + options.timeoutMs;
160
237
  while (deps.now() <= deadline) {
@@ -180,13 +257,13 @@ export async function login(options, overrides = {}) {
180
257
  { ...options, apiBaseUrl },
181
258
  { env: deps.env, homeDir: deps.homeDir, platform: deps.platform },
182
259
  );
183
- writeLine(deps.stdout, `Hive CLI authenticated as API key ${result.credential.keyPrefix}.`);
260
+ writeLine(deps.stdout, terminalText(`Hive CLI authenticated as API key ${result.credential.keyPrefix}.`));
184
261
  writeLine(deps.stdout, `Credential stored at ${configPath}.`);
185
262
  return { configPath, keyPrefix: result.credential.keyPrefix, status: "approved" };
186
263
  }
187
264
  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.");
265
+ if (result.status === "expired") throw new Error("Hive CLI login expired. Run hive3 login again.");
266
+ if (result.status === "completed") throw new Error("Hive CLI login was already completed. Run hive3 login again.");
190
267
  if (result.status === "not_found") throw new Error("Hive CLI login request was not found.");
191
268
  await deps.sleep(pollIntervalMs);
192
269
  }
@@ -0,0 +1,13 @@
1
+ // @ts-check
2
+
3
+ /** Consumer/seller payment management. Never accepts provider credentials or a raw Convex function name. */
4
+ export function createPaymentsClient(client) {
5
+ return {
6
+ list(kind, query = {}) { return client.request("GET", `/payments/${kind}`, { query }); },
7
+ preview(payload) { return client.request("POST", "/payments/preview", { body: payload }); },
8
+ operate(payload, confirmation) {
9
+ // Exactly one request: an unknown financial outcome must be reconciled, never blindly retried.
10
+ return client.request("POST", "/payments/operate", { body: { ...payload, ...confirmation } });
11
+ },
12
+ };
13
+ }
@@ -0,0 +1,127 @@
1
+ // @ts-check
2
+
3
+ import { authenticatedClient, requiredFlagValue, writeJson, writeLine } from "./shared.js";
4
+ import { createPaymentsClient } from "./payments-client.js";
5
+
6
+ export function paymentsUsage() {
7
+ return `Payments (private JSON output)
8
+ hive3 payments history [--limit <1-100>] [--cursor <cursor>]
9
+ hive3 payments subscriptions
10
+ hive3 payments tickets|refunds [--account <seller-id-or-handle>] [--limit <1-100>] [--cursor <cursor>]
11
+ hive3 payments sales [--account <seller-id-or-handle>] [--limit <1-100>] [--cursor <cursor>]
12
+ hive3 payments [preview] checkout subscription|ticket <id> [--provider stripe|paypal]
13
+ hive3 payments [preview] checkout membership --tier honey|swarm|royal [--account <owned-account>]
14
+ hive3 payments [preview] checkout quest-credit <account> --plan-type single|bundle
15
+ hive3 payments [preview] checkout metaverse-time <account> --quantity <1-100-hours>
16
+ hive3 payments quest-credits|metaverse-time [--account <managed-account>] [--limit <1-100>] [--cursor <cursor>]
17
+ hive3 payments [preview] finalize stripe <session-id> --kind membership|subscription|ticket|questCredit|metaverseTime
18
+ hive3 payments [preview] finalize subscription <plan-id> --checkout-intent <id> --paypal-subscription <id>
19
+ hive3 payments [preview] finalize ticket <ticket-id> --order <order-id>
20
+ hive3 payments [preview] subscription cancel|resume|portal <subscription-id>
21
+ hive3 payments [preview] subscription revise <subscription-id> --plan <new-plan-id>
22
+ hive3 payments [preview] membership cancel|resume|portal
23
+ hive3 payments [preview] membership revise --tier honey|swarm|royal
24
+ hive3 payments [preview] refund request <purchased-ticket-id> [--reason <text>]
25
+ hive3 payments [preview] refund approve|reject <refund-request-id> [--note <text>]
26
+
27
+ All operations except lists/preview require --yes --confirm <exact-preview-confirm> --request-id <unique-id>.
28
+ Preview first, inspect the exact financial target/amount, then use its confirm string unchanged.
29
+ Reads need payments:read; previews/writes need payments:write. Managed sellers also need
30
+ communities:read/write, the key's account allowlist, and a current owner/admin role. Team
31
+ scopes never grant access to another buyer's funds. No unattended purchase approval:
32
+ checkout/portal/revision links are private; the owner completes consent in a browser.
33
+ Stripe marketplace plan revision is not supported by the current app. Its portal manages
34
+ payment methods, invoices and cancellation only; subscription revise is PayPal-only.
35
+ Legacy PayPal platform membership management is not supported by the current app.
36
+ Managed-account membership checkout is owner-only; ongoing membership billing uses that
37
+ account's own login, as in the app. Quest credits and metaverse time use Stripe checkout.
38
+ Ticket history omits purchase amounts when Hive3 did not persist the original price;
39
+ it never presents today's ticket price as the historical amount paid.
40
+ No generic payouts, wallet transfers, arbitrary provider administration or account deletion.
41
+ No automatic financial retries. Reuse the same request ID only for the identical request.
42
+ If an outcome is unknown, inspect history/browser/provider status before taking more action.`;
43
+ }
44
+
45
+ const lists = ["history", "subscriptions", "tickets", "refunds", "sales", "quest-credits", "metaverse-time"];
46
+ const verbs = {
47
+ checkout: ["subscription", "ticket", "membership", "quest-credit", "metaverse-time"],
48
+ finalize: ["stripe", "subscription", "ticket"],
49
+ subscription: ["cancel", "resume", "portal", "revise"],
50
+ membership: ["cancel", "resume", "portal", "revise"],
51
+ refund: ["request", "approve", "reject"],
52
+ };
53
+
54
+ export async function runPaymentsCommand(args, deps) {
55
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
56
+ writeLine(deps.stdout, paymentsUsage());
57
+ return;
58
+ }
59
+ const preview = args[0] === "preview";
60
+ const remaining = preview ? args.slice(1) : args;
61
+ const [group, ...rest] = remaining;
62
+ const listing = lists.includes(group);
63
+ if (preview && listing) throw new Error("preview applies only to payment operations");
64
+ if (!listing && !Object.hasOwn(verbs, group)) throw new Error(`Unknown payments command: ${group}`);
65
+ let operation;
66
+ let target;
67
+ let flags;
68
+ if (listing) flags = rest;
69
+ else {
70
+ const [verb, ...tail] = rest;
71
+ if (!verbs[group].includes(verb)) throw new Error(`Unknown payments ${group} operation: ${verb}`);
72
+ operation = `${group}.${verb}`;
73
+ if (group === "membership" || (group === "checkout" && verb === "membership")) { target = "self"; flags = tail; }
74
+ else { target = requiredFlagValue("payment target", tail[0]); flags = tail.slice(1); }
75
+ }
76
+ const values = {};
77
+ const seen = new Set();
78
+ let yes = false;
79
+ for (let index = 0; index < flags.length; index += 1) {
80
+ const flag = flags[index];
81
+ if (seen.has(flag)) throw new Error(`${flag} may only be given once`);
82
+ seen.add(flag);
83
+ if (flag === "--yes") { yes = true; continue; }
84
+ if (!["--account", "--limit", "--cursor", "--provider", "--kind", "--tier", "--plan", "--plan-type", "--quantity", "--order", "--checkout-intent", "--paypal-subscription", "--reason", "--note", "--confirm", "--request-id"].includes(flag)) throw new Error(`Unknown payments option: ${flag}`);
85
+ values[flag] = requiredFlagValue(flag, flags[++index]);
86
+ }
87
+ const accepted = listing ? ["--account", "--limit", "--cursor"] : [
88
+ ...(operation?.startsWith("checkout.") ? ["--provider"] : []),
89
+ ...(operation === "checkout.membership" || operation === "membership.revise" ? ["--tier"] : []),
90
+ ...(operation === "checkout.membership" ? ["--account"] : []),
91
+ ...(operation === "checkout.quest-credit" ? ["--plan-type"] : []),
92
+ ...(operation === "checkout.metaverse-time" ? ["--quantity"] : []),
93
+ ...(operation === "finalize.stripe" ? ["--kind"] : []),
94
+ ...(operation === "finalize.ticket" ? ["--order"] : []),
95
+ ...(operation === "finalize.subscription" ? ["--checkout-intent", "--paypal-subscription"] : []),
96
+ ...(operation === "subscription.revise" ? ["--plan"] : []),
97
+ ...(operation === "refund.request" ? ["--reason"] : []),
98
+ ...(operation === "refund.approve" || operation === "refund.reject" ? ["--note"] : []),
99
+ ...(!preview ? ["--yes", "--confirm", "--request-id"] : []),
100
+ ];
101
+ for (const flag of seen) if (!accepted.includes(flag)) throw new Error(`${flag} is not supported for this payments command`);
102
+ if ((group === "history" || group === "subscriptions") && values["--account"]) throw new Error("Buyer history/subscriptions always belong to the key owner");
103
+ if (values["--limit"] !== undefined && (!Number.isInteger(Number(values["--limit"])) || Number(values["--limit"]) < 1 || Number(values["--limit"]) > 100)) throw new Error("--limit must be an integer from 1 to 100");
104
+ if (values["--provider"] && !["stripe", "paypal"].includes(values["--provider"])) throw new Error("--provider must be stripe or paypal");
105
+ if (values["--kind"] && !["membership", "subscription", "ticket", "questCredit", "metaverseTime"].includes(values["--kind"])) throw new Error("--kind must be membership, subscription, ticket, questCredit or metaverseTime");
106
+ if (values["--tier"] && !["honey", "swarm", "royal"].includes(values["--tier"])) throw new Error("--tier must be honey, swarm or royal");
107
+ if (values["--plan-type"] && !["single", "bundle"].includes(values["--plan-type"])) throw new Error("--plan-type must be single or bundle");
108
+ if (values["--quantity"] !== undefined && (!Number.isInteger(Number(values["--quantity"])) || Number(values["--quantity"]) < 1 || Number(values["--quantity"]) > 100)) throw new Error("--quantity must be an integer from 1 to 100");
109
+ const required = {
110
+ "checkout.membership": ["--tier"], "membership.revise": ["--tier"], "finalize.stripe": ["--kind"],
111
+ "finalize.ticket": ["--order"], "finalize.subscription": ["--checkout-intent", "--paypal-subscription"], "subscription.revise": ["--plan"],
112
+ "checkout.quest-credit": ["--plan-type"], "checkout.metaverse-time": ["--quantity"],
113
+ };
114
+ for (const flag of required[operation] ?? []) if (!values[flag]) throw new Error(`${operation} requires ${flag}`);
115
+ if (!listing && !preview && (!yes || !values["--confirm"] || !values["--request-id"])) throw new Error("Payment operations require --yes, --confirm from preview, and --request-id");
116
+ if (values["--request-id"]?.length > 128) throw new Error("--request-id must be at most 128 characters");
117
+ const client = createPaymentsClient(await authenticatedClient(deps));
118
+ if (listing) {
119
+ writeJson(deps.stdout, await client.list(group, { account: values["--account"], limit: values["--limit"], cursor: values["--cursor"] }));
120
+ return;
121
+ }
122
+ const payload = { operation, target: operation === "checkout.membership" && values["--account"] ? values["--account"] : target };
123
+ const fields = { "--provider": "provider", "--kind": "kind", "--tier": "tier", "--plan": "newPlanId", "--plan-type": "planType", "--order": "orderId", "--checkout-intent": "checkoutIntentId", "--paypal-subscription": "paypalSubscriptionId", "--reason": "reason", "--note": "reviewNote" };
124
+ for (const [flag, field] of Object.entries(fields)) if (values[flag] !== undefined) payload[field] = values[flag];
125
+ if (values["--quantity"] !== undefined) payload.quantity = Number(values["--quantity"]);
126
+ writeJson(deps.stdout, preview ? await client.preview(payload) : await client.operate(payload, { confirmed: true, confirm: values["--confirm"], requestId: values["--request-id"] }));
127
+ }
@@ -0,0 +1,24 @@
1
+ // @ts-check
2
+
3
+ /** Fixed seller resources only; buyer lifecycle lives under payments. */
4
+ export function createSellingClient(client) {
5
+ return {
6
+ listProducts(account) { return client.request("GET", "/products", { query: { account } }); },
7
+ getProduct(id) { return client.request("GET", `/products/${encodeURIComponent(id)}`); },
8
+ createProduct(payload, account, requestId) { return client.request("POST", "/products", { query: { account }, body: { ...payload, confirmed: true, requestId }, idempotencyKey: requestId }); },
9
+ deleteProduct(id, requestId) { return client.request("DELETE", `/products/${encodeURIComponent(id)}`, { body: { confirmed: true, requestId }, idempotencyKey: requestId }); },
10
+ listPlans(productId) { return client.request("GET", `/products/${encodeURIComponent(productId)}/plans`); },
11
+ getPlan(id) { return client.request("GET", `/subscriptions/${encodeURIComponent(id)}`); },
12
+ createPlan(productId, payload, requestId) { return client.request("POST", `/products/${encodeURIComponent(productId)}/plans`, { body: { ...payload, confirmed: true, requestId }, idempotencyKey: requestId }); },
13
+ updatePlan(id, payload, requestId) { return client.request("PATCH", `/subscriptions/${encodeURIComponent(id)}`, { body: { ...payload, confirmed: true, requestId }, idempotencyKey: requestId }); },
14
+ setPlanStatus(id, status, requestId) { return client.request("POST", `/subscriptions/${encodeURIComponent(id)}/${status}`, { body: { confirmed: true, requestId }, idempotencyKey: requestId }); },
15
+ deletePlan(id, requestId) { return client.request("DELETE", `/subscriptions/${encodeURIComponent(id)}`, { body: { confirmed: true, requestId }, idempotencyKey: requestId }); },
16
+ listTickets(query) { return client.request("GET", "/tickets", { query }); },
17
+ ticketEntities(account) { return client.request("GET", "/tickets/entities", { query: { account } }); },
18
+ myTickets(query) { return client.request("GET", "/tickets/mine", { query }); },
19
+ getTicket(id) { return client.request("GET", `/tickets/${encodeURIComponent(id)}`); },
20
+ createTicket(payload, requestId) { return client.request("POST", "/tickets", { body: { ...payload, confirmed: true, requestId }, idempotencyKey: requestId }); },
21
+ updateTicket(id, payload, requestId) { return client.request("PATCH", `/tickets/${encodeURIComponent(id)}`, { body: { ...payload, confirmed: true, requestId }, idempotencyKey: requestId }); },
22
+ removeTicket(id, requestId) { return client.request("DELETE", `/tickets/${encodeURIComponent(id)}`, { body: { confirmed: true, requestId }, idempotencyKey: requestId }); },
23
+ };
24
+ }
@@ -0,0 +1,157 @@
1
+ // @ts-check
2
+ import { randomUUID } from "node:crypto";
3
+ import { authenticatedClient, readJsonObject, requiredFlagValue, writeJson, writeLine } from "./shared.js";
4
+ import { createSellingClient } from "./selling-client.js";
5
+
6
+ export function sellingUsage() {
7
+ return `Seller products, subscription plans and tickets (JSON output)
8
+ hive3 products list [--account <seller>]
9
+ hive3 products get <id>
10
+ hive3 products create --title <title> [--description <text>] [--image-url <url>] [--account <seller>] --yes
11
+ hive3 products delete <id> --yes
12
+ hive3 subscriptions list --product <product-id>
13
+ hive3 subscriptions get <plan-id>
14
+ hive3 subscriptions create --product <product-id> --name <name> --amount <decimal> --interval monthly|yearly [--currency USD] [--description <text>] --yes
15
+ hive3 subscriptions update <plan-id> --name <name> --amount <decimal> --currency <code> --interval monthly|yearly [--description <text>] --yes
16
+ hive3 subscriptions activate|deactivate|delete <plan-id> --yes
17
+ hive3 tickets list [--account <seller>] [--limit <1-100>] [--cursor <cursor>]
18
+ hive3 tickets entities [--account <seller>]
19
+ hive3 tickets mine [--limit <1-100>] [--cursor <cursor>]
20
+ hive3 tickets get <id>
21
+ hive3 tickets create --product <id> --name <name> --amount <decimal> --entity-type event|course|quest|coordination --entity-id <id> [--currency USD] [--description <text>] [--status active|inactive] --yes
22
+ hive3 tickets update <id> [--name <name>] [--description <text>] [--amount <decimal>] [--currency <code>] [--status active|inactive] --yes
23
+ hive3 tickets attach <id> --entity-type event|course|quest|coordination --entity-id <id> --yes
24
+ hive3 tickets remove <id> --yes
25
+
26
+ Create/update/attach accept --file <JSON-object> instead of field flags.
27
+ All writes accept --idempotency-key <key>.
28
+ All writes require --yes; provider attempts are never automatically retried.
29
+ Keep an idempotency key to safely replay the same request. If an external attempt
30
+ failed, inspect provider/app state before intentionally using a new key.
31
+ products/subscriptions require payments:read/write; tickets require tickets:read/write.
32
+ Managed sellers also require communities:read/write, a current owner/admin role and
33
+ the key's allowlist. Starting sales requires a claimed paid seller and ready payment provider.
34
+ PayPal plan pricing changes require a replacement plan; metadata-only edits are allowed.
35
+ Seller currencies match the app: USD, EUR, GBP.
36
+ Deleting products/plans hides them from future sales; existing subscriptions and
37
+ purchase/refund history are preserved. Removing a ticket deactivates it. Sold tickets
38
+ cannot be moved to another resource. Buyer subscriptions are under payments.`;
39
+ }
40
+
41
+ const FIELDS = { "--title": "title", "--name": "name", "--description": "description", "--image-url": "imageUrl", "--amount": "amount", "--currency": "currency", "--interval": "interval", "--product": "productId", "--entity-type": "entityType", "--entity-id": "entityId", "--status": "status" };
42
+ const WRITE = ["--yes", "--idempotency-key", "--file"];
43
+ function parse(args, allowed) {
44
+ const values = {};
45
+ const positionals = [];
46
+ const seen = new Set();
47
+ for (let index = 0; index < args.length; index += 1) {
48
+ const flag = args[index];
49
+ if (!flag.startsWith("--")) { positionals.push(flag); continue; }
50
+ if (!allowed.includes(flag)) throw new Error(`Unknown seller option: ${flag}`);
51
+ if (seen.has(flag)) throw new Error(`${flag} may only be given once`);
52
+ seen.add(flag);
53
+ values[flag] = flag === "--yes" ? true : requiredFlagValue(flag, args[++index]);
54
+ }
55
+ if (positionals.length > 1) throw new Error(`Unexpected seller argument: ${positionals[1]}`);
56
+ return { values, id: positionals[0] };
57
+ }
58
+ function requireField(payload, field) {
59
+ if (typeof payload[field] !== "string" || !payload[field].trim()) throw new Error(`${field} is required`);
60
+ }
61
+ async function writePayload(values, fields) {
62
+ const payload = values["--file"] ? await readJsonObject(values["--file"]) : {};
63
+ for (const [flag, field] of Object.entries(FIELDS)) if (fields.includes(flag) && values[flag] !== undefined) payload[field] = values[flag];
64
+ if (payload.amount !== undefined && (typeof payload.amount !== "string" || !/^\d{1,7}(\.\d{1,2})?$/.test(payload.amount) || Number(payload.amount) <= 0 || Number(payload.amount) > 1_000_000)) throw new Error("amount must be a positive decimal up to 1000000 with at most two decimal places");
65
+ if (payload.currency !== undefined) {
66
+ if (typeof payload.currency !== "string" || !/^[A-Za-z]{3}$/.test(payload.currency)) throw new Error("currency must be a three-letter currency code");
67
+ payload.currency = payload.currency.toUpperCase();
68
+ if (!["USD", "EUR", "GBP"].includes(payload.currency)) throw new Error("Seller currency must be USD, EUR, or GBP");
69
+ }
70
+ if (payload.interval !== undefined && !["monthly", "yearly"].includes(payload.interval)) throw new Error("interval must be monthly or yearly");
71
+ if (payload.status !== undefined && !["active", "inactive"].includes(payload.status)) throw new Error("status must be active or inactive");
72
+ if (payload.entityType !== undefined && !["event", "course", "quest", "coordination"].includes(payload.entityType)) throw new Error("entity-type must be event, course, quest or coordination");
73
+ return payload;
74
+ }
75
+ function writeId(values) {
76
+ if (!values["--yes"]) throw new Error("Seller writes require --yes");
77
+ const id = values["--idempotency-key"] ?? randomUUID();
78
+ if (!id.trim() || id.length > 128) throw new Error("--idempotency-key must be 1–128 characters");
79
+ return id;
80
+ }
81
+ function paging(values) {
82
+ const limit = values["--limit"] === undefined ? undefined : Number(values["--limit"]);
83
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100)) throw new Error("--limit must be a whole number from 1 to 100");
84
+ return { account: values["--account"], cursor: values["--cursor"], limit };
85
+ }
86
+
87
+ /** Parent dispatches these three groups here before the legacy area dispatcher. */
88
+ export async function runSellingCommand(group, args, deps) {
89
+ if (!args.length || args.includes("--help") || args.includes("-h")) { writeLine(deps.stdout, sellingUsage()); return; }
90
+ const [action, ...rest] = args;
91
+ const productFields = ["--title", "--description", "--image-url"];
92
+ const planFields = ["--name", "--description", "--amount", "--currency", "--interval"];
93
+ const ticketFields = ["--product", "--name", "--description", "--amount", "--currency", "--entity-type", "--entity-id", "--status"];
94
+ let fields = [];
95
+ let allowed = [];
96
+ const read = ["list", "get", "mine", "entities"].includes(action);
97
+ if (group === "products") {
98
+ if (action === "list") allowed = ["--account"];
99
+ else if (action === "get") allowed = [];
100
+ else if (action === "create") { fields = productFields; allowed = [...WRITE, ...fields, "--account"]; }
101
+ else if (action === "delete") allowed = WRITE;
102
+ else throw new Error(`Unknown products action: ${action}`);
103
+ } else if (group === "subscriptions") {
104
+ if (action === "list") allowed = ["--product"];
105
+ else if (action === "get") allowed = [];
106
+ else if (action === "create" || action === "update") { fields = [...planFields, ...(action === "create" ? ["--product"] : [])]; allowed = [...WRITE, ...fields]; }
107
+ else if (["activate", "deactivate", "delete"].includes(action)) allowed = WRITE;
108
+ else throw new Error(`Unknown subscriptions action: ${action}`);
109
+ } else if (group === "tickets") {
110
+ if (action === "list") allowed = ["--account", "--limit", "--cursor"];
111
+ else if (action === "mine") allowed = ["--limit", "--cursor"];
112
+ else if (action === "entities") allowed = ["--account"];
113
+ else if (action === "get") allowed = [];
114
+ else if (action === "create" || action === "update" || action === "attach") { fields = action === "attach" ? ["--entity-type", "--entity-id"] : ticketFields.filter(field => action === "create" || field !== "--product"); allowed = [...WRITE, ...fields]; }
115
+ else if (action === "remove") allowed = WRITE;
116
+ else throw new Error(`Unknown tickets action: ${action}`);
117
+ } else throw new Error(`Unknown seller group: ${group}`);
118
+ if (fields.length === 0) allowed = allowed.filter(flag => flag !== "--file");
119
+ const { values, id } = parse(rest, allowed);
120
+ const needsId = !["create", "list", "mine", "entities"].includes(action);
121
+ if (needsId && !id) throw new Error(`${group} ${action} requires an id`);
122
+ if (!needsId && id) throw new Error(`Unexpected seller argument: ${id}`);
123
+ const requestId = read ? undefined : writeId(values);
124
+ const payload = read ? {} : await writePayload(values, fields);
125
+ if (group === "products" && action === "create") requireField(payload, "title");
126
+ if (group === "subscriptions" && (action === "create" || action === "update")) {
127
+ for (const field of ["name", "amount", "interval", ...(action === "update" ? ["currency"] : ["productId"])]) requireField(payload, field);
128
+ }
129
+ if (group === "tickets" && action === "create") for (const field of ["productId", "name", "amount", "entityType", "entityId"]) requireField(payload, field);
130
+ if (group === "tickets" && action === "attach") for (const field of ["entityType", "entityId"]) requireField(payload, field);
131
+ if (group === "tickets" && action === "update" && !Object.keys(payload).length) throw new Error("tickets update needs at least one field");
132
+ const query = paging(values);
133
+ const client = createSellingClient(await authenticatedClient(deps));
134
+ let result;
135
+ if (group === "products") {
136
+ if (action === "list") result = await client.listProducts(values["--account"]);
137
+ else if (action === "get") result = await client.getProduct(id);
138
+ else if (action === "create") result = await client.createProduct(payload, values["--account"], requestId);
139
+ else result = await client.deleteProduct(id, requestId);
140
+ } else if (group === "subscriptions") {
141
+ if (action === "list") result = await client.listPlans(requiredFlagValue("--product", values["--product"]));
142
+ else if (action === "get") result = await client.getPlan(id);
143
+ else if (action === "create") { const { productId, ...plan } = payload; result = await client.createPlan(productId, plan, requestId); }
144
+ else if (action === "update") result = await client.updatePlan(id, payload, requestId);
145
+ else if (action === "delete") result = await client.deletePlan(id, requestId);
146
+ else result = await client.setPlanStatus(id, action, requestId);
147
+ } else {
148
+ if (action === "list") result = await client.listTickets(query);
149
+ else if (action === "mine") result = await client.myTickets(query);
150
+ else if (action === "entities") result = await client.ticketEntities(values["--account"]);
151
+ else if (action === "get") result = await client.getTicket(id);
152
+ else if (action === "create") result = await client.createTicket(payload, requestId);
153
+ else if (action === "remove") result = await client.removeTicket(id, requestId);
154
+ else result = await client.updateTicket(id, payload, requestId);
155
+ }
156
+ writeJson(deps.stdout, result);
157
+ }
package/src/shared.js ADDED
@@ -0,0 +1,102 @@
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
+ // C0 except \t and \n, DEL, C1, and bidi embedding/override/isolate/mark controls.
13
+ const UNSAFE_TERMINAL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
14
+ // JSON.stringify already escapes C0; these survive it raw and can drive or reorder a terminal.
15
+ const UNSAFE_JSON_CHARS = /[\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
16
+
17
+ /**
18
+ * Server-provided text (names, messages, error text) must pass through this before it
19
+ * reaches a terminal so it cannot emit escape sequences or visually reorder output.
20
+ * @param {unknown} value
21
+ */
22
+ export function terminalText(value) {
23
+ return String(value).replace(UNSAFE_TERMINAL_CHARS, "");
24
+ }
25
+
26
+ export function writeJson(stream, value) {
27
+ const json = String(JSON.stringify(value, null, 2))
28
+ .replace(UNSAFE_JSON_CHARS, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
29
+ writeLine(stream, json);
30
+ }
31
+
32
+ export function requiredFlagValue(flag, value) {
33
+ if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
34
+ return value;
35
+ }
36
+
37
+ export function parseBoolean(value, flag) {
38
+ if (value === "true" || value === "1" || value === "yes") return true;
39
+ if (value === "false" || value === "0" || value === "no") return false;
40
+ throw new Error(`${flag} must be true or false`);
41
+ }
42
+
43
+ export async function readJsonObject(file) {
44
+ const parsed = JSON.parse(await readFile(file, "utf8"));
45
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
46
+ throw new Error(`${file} must contain a JSON object`);
47
+ }
48
+ return parsed;
49
+ }
50
+
51
+ export async function authenticatedClient(deps) {
52
+ const config = await loadConfig({ env: deps.env, homeDir: deps.homeDir, platform: deps.platform });
53
+ if (!config) throw new HiveApiError("Not logged in. Run hive3 login first.", { code: "auth_required", status: 401 });
54
+ return createApiClient({ apiBaseUrl: config.apiBaseUrl, apiKey: config.apiKey, fetch: deps.fetch });
55
+ }
56
+
57
+ const UPLOAD_PATH = "/internal/storage/upload";
58
+ const loopbackHosts = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
59
+
60
+ /**
61
+ * Refuse any server-returned upload URL that is not an https (loopback-only http)
62
+ * Hive storage endpoint. The API issues `<CONVEX_SITE_URL>/internal/storage/upload?token=...`,
63
+ * so the host must be the API host itself or a Convex site/cloud host.
64
+ * @param {string} uploadUrl
65
+ * @param {string} apiBaseUrl
66
+ */
67
+ export function assertTrustedUploadUrl(uploadUrl, apiBaseUrl) {
68
+ let target;
69
+ try {
70
+ target = new URL(uploadUrl);
71
+ } catch {
72
+ throw new Error("Refusing to upload: the server returned an invalid upload URL.");
73
+ }
74
+ const api = new URL(apiBaseUrl);
75
+ const loopback = loopbackHosts.has(target.hostname);
76
+ const secure = target.protocol === "https:" || (target.protocol === "http:" && loopback && loopbackHosts.has(api.hostname));
77
+ const trustedHost = target.hostname === api.hostname
78
+ || target.hostname.endsWith(".convex.site")
79
+ || target.hostname.endsWith(".convex.cloud")
80
+ || (loopback && loopbackHosts.has(api.hostname));
81
+ if (!secure || !trustedHost || target.username || target.password || target.pathname !== UPLOAD_PATH) {
82
+ throw new Error(
83
+ `Refusing to upload: the server returned an upload URL that is not an https Hive storage endpoint (${target.protocol}//${target.host}).`,
84
+ );
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Validate the issued upload URL, then POST the file bytes to it (no Hive credentials are sent).
90
+ * @returns {Promise<{ ok: boolean, parsed: any, status: number }>}
91
+ */
92
+ export async function postFileToUploadUrl(client, deps, uploadUrl, filePath, contentType, bytes = undefined) {
93
+ assertTrustedUploadUrl(uploadUrl, client.apiBaseUrl);
94
+ const response = await deps.fetch(uploadUrl, {
95
+ body: new Blob([bytes ?? await readFile(filePath)], { type: contentType }),
96
+ headers: { "Content-Type": contentType },
97
+ method: "POST",
98
+ redirect: "error",
99
+ });
100
+ const text = await response.text();
101
+ return { ok: response.ok, parsed: text ? JSON.parse(text) : {}, status: response.status };
102
+ }