@hive3/cli 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
package/src/login.js CHANGED
@@ -4,24 +4,31 @@ 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
- export const DEFAULT_LABEL = "Hive CLI";
11
+ export const DEFAULT_LABEL = "Hive3 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
21
  "Usage: hive3 login [options]",
17
22
  "",
18
23
  "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.",
24
+ "Creating a CLI key needs Honey Bee or above.",
20
25
  "",
21
26
  "Options:",
22
27
  " --access <read|full> Permission bundle to approve; omit to choose in browser",
28
+ " --messages-access <read|full> Separately request private conversations and messaging",
23
29
  " --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)",
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",
25
32
  " --label <label> Name shown on the approval page",
26
33
  " --scope <scope> Advanced: request an exact API scope, repeatable",
27
34
  " --timeout-ms <ms> Login polling timeout",
@@ -29,6 +36,7 @@ export function loginUsage() {
29
36
  " -h, --help Show help",
30
37
  "",
31
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.",
32
40
  ].join("\n");
33
41
  }
34
42
 
@@ -39,13 +47,15 @@ function requiredFlagValue(flag, value) {
39
47
 
40
48
  export function parseLoginArgs(args, env = process.env) {
41
49
  const options = {
50
+ allowCustomApiUrl: false,
42
51
  apiBaseUrl: env.HIVE_API_URL || DEFAULT_API_BASE_URL,
43
- appUrl: env.HIVE_APP_URL || DEFAULT_APP_URL,
52
+ appUrl: env.HIVE_APP_URL || "",
44
53
  label: DEFAULT_LABEL,
45
54
  noOpen: false,
46
55
  permissionMode: DEFAULT_PERMISSION_MODE,
47
56
  permissionModeExplicit: false,
48
57
  scopes: [],
58
+ messagesAccess: undefined,
49
59
  timeoutMs: DEFAULT_TIMEOUT_MS,
50
60
  };
51
61
 
@@ -53,12 +63,20 @@ export function parseLoginArgs(args, env = process.env) {
53
63
  const flag = args[index];
54
64
  if (flag === "--no-open") {
55
65
  options.noOpen = true;
66
+ } else if (flag === "--allow-custom-api-url") {
67
+ options.allowCustomApiUrl = true;
56
68
  } else if (flag === "--access" || flag === "--permission") {
57
69
  index += 1;
58
70
  const value = requiredFlagValue(flag, args[index]);
59
71
  if (value !== "read" && value !== "full") throw new Error(`${flag} must be read or full`);
60
72
  options.permissionMode = value;
61
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;
62
80
  } else if (flag === "--api-url") {
63
81
  index += 1;
64
82
  options.apiBaseUrl = requiredFlagValue(flag, args[index]);
@@ -87,9 +105,60 @@ export function parseLoginArgs(args, env = process.env) {
87
105
  if (options.permissionModeExplicit && options.scopes.length > 0) {
88
106
  throw new Error("--access cannot be combined with --scope. Use one permission bundle or exact scopes.");
89
107
  }
108
+ if (!options.appUrl) options.appUrl = defaultAppUrl(options.apiBaseUrl);
90
109
  return { help: false, options };
91
110
  }
92
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
+
93
162
  export function isSafeBrowserUrl(url) {
94
163
  let parsed;
95
164
  try {
@@ -130,19 +199,20 @@ function defaultDeps() {
130
199
  openBrowser,
131
200
  platform: process.platform,
132
201
  sleep,
202
+ stderr: process.stderr,
133
203
  stdout: process.stdout,
134
204
  };
135
205
  }
136
206
 
137
- function writeLine(stream, message = "") {
138
- stream.write(`${message}\n`);
139
- }
140
-
141
207
  export async function login(options, overrides = {}) {
142
208
  const deps = { ...defaultDeps(), ...overrides };
143
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
+ }
144
214
  const payload = {
145
- appUrl: options.appUrl,
215
+ appUrl,
146
216
  label: options.label,
147
217
  };
148
218
  if (options.scopes.length > 0) {
@@ -150,6 +220,7 @@ export async function login(options, overrides = {}) {
150
220
  } else {
151
221
  payload.permissionMode = options.permissionMode || DEFAULT_PERMISSION_MODE;
152
222
  }
223
+ if (options.messagesAccess !== undefined) payload.messagesAccess = options.messagesAccess;
153
224
  const start = await postJson(deps.fetch, `${apiBaseUrl}/cli/auth/start`, payload);
154
225
  const data = start.data;
155
226
  // A malformed server response must not turn the poll loop into a busy loop
@@ -157,9 +228,10 @@ export async function login(options, overrides = {}) {
157
228
  const rawPollIntervalMs = Number(data.pollIntervalMs);
158
229
  const pollIntervalMs = Number.isFinite(rawPollIntervalMs) && rawPollIntervalMs >= 500 ? rawPollIntervalMs : 2000;
159
230
 
160
- writeLine(deps.stdout, `Open this URL to approve Hive CLI access: ${data.approvalUrl}`);
161
- writeLine(deps.stdout, `Code: ${data.code} (type it on the approval page)`);
162
- 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 Hive3 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);
163
235
 
164
236
  const deadline = deps.now() + options.timeoutMs;
165
237
  while (deps.now() <= deadline) {
@@ -185,15 +257,15 @@ export async function login(options, overrides = {}) {
185
257
  { ...options, apiBaseUrl },
186
258
  { env: deps.env, homeDir: deps.homeDir, platform: deps.platform },
187
259
  );
188
- writeLine(deps.stdout, `Hive CLI authenticated as API key ${result.credential.keyPrefix}.`);
260
+ writeLine(deps.stdout, terminalText(`Hive3 CLI authenticated as API key ${result.credential.keyPrefix}.`));
189
261
  writeLine(deps.stdout, `Credential stored at ${configPath}.`);
190
262
  return { configPath, keyPrefix: result.credential.keyPrefix, status: "approved" };
191
263
  }
192
- if (result.status === "denied") throw new Error("Hive CLI login was denied in the browser.");
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.");
195
- if (result.status === "not_found") throw new Error("Hive CLI login request was not found.");
264
+ if (result.status === "denied") throw new Error("Hive3 CLI login was denied in the browser.");
265
+ if (result.status === "expired") throw new Error("Hive3 CLI login expired. Run hive3 login again.");
266
+ if (result.status === "completed") throw new Error("Hive3 CLI login was already completed. Run hive3 login again.");
267
+ if (result.status === "not_found") throw new Error("Hive3 CLI login request was not found.");
196
268
  await deps.sleep(pollIntervalMs);
197
269
  }
198
- throw new Error("Hive CLI login timed out.");
270
+ throw new Error("Hive3 CLI login timed out.");
199
271
  }
@@ -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 CHANGED
@@ -9,8 +9,24 @@ export function writeLine(stream, message = "") {
9
9
  stream.write(`${message}\n`);
10
10
  }
11
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
+
12
26
  export function writeJson(stream, value) {
13
- writeLine(stream, JSON.stringify(value, null, 2));
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);
14
30
  }
15
31
 
16
32
  export function requiredFlagValue(flag, value) {
@@ -73,10 +89,10 @@ export function assertTrustedUploadUrl(uploadUrl, apiBaseUrl) {
73
89
  * Validate the issued upload URL, then POST the file bytes to it (no Hive credentials are sent).
74
90
  * @returns {Promise<{ ok: boolean, parsed: any, status: number }>}
75
91
  */
76
- export async function postFileToUploadUrl(client, deps, uploadUrl, filePath, contentType) {
92
+ export async function postFileToUploadUrl(client, deps, uploadUrl, filePath, contentType, bytes = undefined) {
77
93
  assertTrustedUploadUrl(uploadUrl, client.apiBaseUrl);
78
94
  const response = await deps.fetch(uploadUrl, {
79
- body: new Blob([await readFile(filePath)], { type: contentType }),
95
+ body: new Blob([bytes ?? await readFile(filePath)], { type: contentType }),
80
96
  headers: { "Content-Type": contentType },
81
97
  method: "POST",
82
98
  redirect: "error",
@@ -0,0 +1,16 @@
1
+ // @ts-check
2
+
3
+ /** Connect management only. The API base already includes /api/v1. */
4
+ export function createStripeClient(client) {
5
+ return {
6
+ status(query) {
7
+ return client.request("GET", "/payments/stripe/status", { query });
8
+ },
9
+ operate(operation, query, confirm) {
10
+ return client.request("POST", `/payments/stripe/${operation}`, {
11
+ query,
12
+ body: confirm === undefined ? {} : { confirm },
13
+ });
14
+ },
15
+ };
16
+ }