@hive3/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # Hive CLI
2
+
3
+ Installable command-line client for Hive's person-owned public API credentials. The CLI always uses the signed-in person's account key. Communities do not receive API keys; community actions are available only when `hive capabilities` shows a current role for that person.
4
+
5
+ ## Install And Login
6
+
7
+ ```bash
8
+ pnpm --filter @hive3/cli check
9
+ hive login
10
+ hive whoami
11
+ hive capabilities
12
+ ```
13
+
14
+ The CLI stores credentials in the OS config directory, or `HIVE_CONFIG_HOME` when set. It prints approval URLs, codes, key prefixes, and config paths, but never prints the API key secret after login completion.
15
+
16
+ Useful environment overrides:
17
+
18
+ - `HIVE_API_URL`: public API base URL, default `https://app.hive3.tech/api/v1`
19
+ - `HIVE_APP_URL`: browser approval app URL, default `https://app.hive3.tech`
20
+ - `HIVE_CONFIG_HOME`: test/custom config directory
21
+
22
+ ## Scopes
23
+
24
+ - `account:read` and `account:write`: profile, account preferences, wallets visibility, NFT exposure, export/deletion requests, uploads, and builder config.
25
+ - `posts:read` and `posts:write`: posts and comments.
26
+ - `resources:read` and `resources:write`: events, courses, content, quests, jobs, participant workflows, evidence, attendance, progress, and applications.
27
+ - `communities:read`, `communities:moderate`, and `communities:write`: capability discovery and current-role community membership/member workflows.
28
+
29
+ Scopes are necessary but not sufficient. Resource manager routes also require the person behind the key to be the owner or have the current community role. If `hive capabilities` returns an empty community list, personal commands can still work, but community-scoped commands should not be attempted.
30
+
31
+ ## Resource CRUD
32
+
33
+ All resource commands print JSON.
34
+
35
+ ```bash
36
+ hive posts list
37
+ hive posts create --body "Hello Hive"
38
+ hive events create --title "Launch" --description "Details" --visibility public
39
+ hive courses create --file course.json --idempotency-key course-001
40
+ hive content update <content-id> --file content.json
41
+ hive quests create --file quest.json
42
+ hive jobs archive <job-id>
43
+ ```
44
+
45
+ Supported resource families are `posts`, `events`, `courses`, `content`, `quests`, and `jobs`. Supported CRUD actions are `list`, `create`, `update <id>`, and `archive <id>`.
46
+
47
+ Community-targeted creates use the same person credential and the person's live community role:
48
+
49
+ ```bash
50
+ hive posts create --body "Moderator update" --owner-type community --community-id <community-id>
51
+ ```
52
+
53
+ Complex payloads should use `--file <json>`. The JSON file must contain an object and is merged with command-line flags.
54
+
55
+ ## Uploads
56
+
57
+ Upload images or documents first, then attach the returned storage ID through a profile/resource/workflow JSON payload.
58
+
59
+ ```bash
60
+ hive upload ./banner.png --purpose image
61
+ hive upload ./resume.pdf --purpose document
62
+ ```
63
+
64
+ Allowed image types: GIF, JPEG, PNG, WebP up to 8 MB. Allowed document types: PDF, DOC, DOCX, Markdown, plain text up to 25 MB.
65
+
66
+ ## Workflow Commands
67
+
68
+ Workflow commands use `/api/v1/workflows/*` and print stable JSON for agents.
69
+
70
+ ```bash
71
+ hive events participants <event-id>
72
+ hive events rsvp <event-id> --enroll true
73
+ hive events approve <event-id> <enrollment-id>
74
+ hive events deny <event-id> <enrollment-id>
75
+ hive events attendance <event-id> <enrollment-id>
76
+
77
+ hive courses enroll <course-id>
78
+ hive courses enrollments <course-id>
79
+ hive courses approve <course-id> <person-id>
80
+ hive courses deny <course-id> <person-id>
81
+ hive courses complete <course-id> <lesson-id>
82
+
83
+ hive quests enroll <quest-id>
84
+ hive quests enrollments <quest-id>
85
+ hive quests approve <quest-id> <enrollment-id>
86
+ hive quests deny <quest-id> <enrollment-id>
87
+ hive quests evidence submit <quest-id> --objective-id <objective-id> --content "https://proof.example" --file evidence.json
88
+ hive quests evidence list <quest-id> --status pending
89
+ hive quests evidence approve <quest-id> <evidence-id>
90
+
91
+ hive jobs apply <job-id> --file application.json
92
+ hive jobs applications <job-id>
93
+ hive jobs applications
94
+ hive jobs status <application-id> --status accepted
95
+ ```
96
+
97
+ Job application JSON example:
98
+
99
+ ```json
100
+ {
101
+ "resume": {
102
+ "storageId": "kg...",
103
+ "fileName": "resume.pdf",
104
+ "contentType": "application/pdf",
105
+ "byteSize": 124000
106
+ },
107
+ "coverLetter": {
108
+ "storageId": "kg...",
109
+ "fileName": "cover-letter.pdf",
110
+ "contentType": "application/pdf",
111
+ "byteSize": 84000
112
+ }
113
+ }
114
+ ```
115
+
116
+ Quest evidence JSON example:
117
+
118
+ ```json
119
+ {
120
+ "attachments": [
121
+ {
122
+ "storageId": "kg...",
123
+ "fileName": "proof.pdf",
124
+ "contentType": "application/pdf",
125
+ "byteSize": 100000
126
+ }
127
+ ]
128
+ }
129
+ ```
130
+
131
+ ## Personal Account Commands
132
+
133
+ ```bash
134
+ hive profile get
135
+ hive profile update --name "Ada" --image-storage-id <storage-id>
136
+ hive profile access --type open
137
+ hive profile overview save --file overview.json
138
+ hive account preferences --theme dark
139
+ hive account export
140
+ hive wallets default <wallet-address>
141
+ hive wallets visibility <wallet-address> --public true
142
+ hive nfts visibility --public false
143
+ hive notifications list
144
+ hive comments create --post-id <post-id> --content "Nice work"
145
+ hive communities applications <community-id>
146
+ hive communities approve <application-id>
147
+ ```
148
+
149
+ Destructive or high-risk commands require explicit arguments such as exact IDs or confirmations. `archive`, member removal, role changes, application review, attendance recording, account deletion requests, and evidence/applicant decisions should be treated as confirmation-worthy in agent workflows.
150
+
151
+ ## Excluded Operations
152
+
153
+ The CLI intentionally excludes wallet custody/signing/transfers, payment capture, credential minting/deployment/signature flows, private DMs, team/admin tools, migrations/imports/smoke helpers, community-owned API keys, community hard deletion, and arbitrary secret-bearing integration writes.
package/bin/hive.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { main } from "../src/commands.js";
4
+
5
+ process.exitCode = await main(process.argv.slice(2));
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@hive3/cli",
3
+ "version": "0.1.0",
4
+ "description": "Command-line client for Hive's public API.",
5
+ "type": "module",
6
+ "bin": {
7
+ "hive": "bin/hive.js",
8
+ "hive3": "bin/hive.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md",
14
+ "package.json"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "scripts": {
20
+ "check": "node --check bin/hive.js && node --check src/api-client.js && node --check src/commands.js && node --check src/config.js && node --check src/extended-commands.js && node --check src/login.js",
21
+ "test": "node --test test/*.test.mjs"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ }
26
+ }
@@ -0,0 +1,273 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * @typedef {"posts" | "events" | "courses" | "content" | "quests" | "jobs"} ResourceKind
5
+ * @typedef {"GET" | "POST" | "PATCH" | "DELETE"} HttpMethod
6
+ * @typedef {object} ApiClientOptions
7
+ * @property {string} apiBaseUrl
8
+ * @property {string=} apiKey
9
+ * @property {typeof fetch=} fetch
10
+ */
11
+
12
+ export const resourceKinds = ["posts", "events", "courses", "content", "quests", "jobs"];
13
+
14
+ export class HiveApiError extends Error {
15
+ constructor(message, options = {}) {
16
+ super(message);
17
+ this.name = "HiveApiError";
18
+ this.code = options.code || "api_error";
19
+ this.status = options.status || 0;
20
+ this.requiredScopes = options.requiredScopes || [];
21
+ this.retryAfterSeconds = options.retryAfterSeconds ?? null;
22
+ }
23
+ }
24
+
25
+ export function isResourceKind(value) {
26
+ return resourceKinds.includes(value);
27
+ }
28
+
29
+ // Loopback hosts are the only place plain http may carry the Bearer key /
30
+ // poll token; everything else must be TLS.
31
+ const loopbackHosts = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
32
+
33
+ export function normalizeBaseUrl(value) {
34
+ const baseUrl = value.replace(/\/+$/, "");
35
+ let parsed;
36
+ try {
37
+ parsed = new URL(baseUrl);
38
+ } catch {
39
+ throw new Error("Invalid Hive API URL. Provide an absolute URL such as https://app.hive3.tech/api/v1.");
40
+ }
41
+ const loopbackHttp = parsed.protocol === "http:" && loopbackHosts.has(parsed.hostname);
42
+ if (parsed.protocol !== "https:" && !loopbackHttp) {
43
+ throw new Error(
44
+ "Refusing to send Hive credentials over an insecure connection. Use an https:// API URL (http:// is only allowed for localhost, 127.0.0.1, or ::1).",
45
+ );
46
+ }
47
+ return baseUrl;
48
+ }
49
+
50
+ function requireFetch(fetchImpl) {
51
+ if (typeof fetchImpl !== "function") {
52
+ throw new Error("Hive CLI requires Node.js 20 or newer with global fetch support.");
53
+ }
54
+ return fetchImpl;
55
+ }
56
+
57
+ async function parseJsonResponse(response, url) {
58
+ const text = await response.text();
59
+ if (!text.trim()) return null;
60
+ try {
61
+ return JSON.parse(text);
62
+ } catch {
63
+ throw new HiveApiError(`Hive API returned non-JSON response from ${url}`, {
64
+ code: "invalid_response",
65
+ status: response.status,
66
+ });
67
+ }
68
+ }
69
+
70
+ export async function postJson(fetchImpl, url, payload) {
71
+ const response = await requireFetch(fetchImpl)(url, {
72
+ body: JSON.stringify(payload),
73
+ headers: { "Content-Type": "application/json" },
74
+ method: "POST",
75
+ });
76
+ const parsed = await parseJsonResponse(response, url);
77
+ if (!response.ok) {
78
+ const retryAfterHeader = Number(response.headers?.get?.("retry-after"));
79
+ throw new HiveApiError(parsed?.error?.message ?? `Hive API request failed with status ${response.status}`, {
80
+ code: parsed?.error?.code,
81
+ requiredScopes: parsed?.error?.requiredScopes,
82
+ retryAfterSeconds: Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader : undefined,
83
+ status: response.status,
84
+ });
85
+ }
86
+ return parsed;
87
+ }
88
+
89
+ function appendQuery(url, query = {}) {
90
+ for (const [key, value] of Object.entries(query)) {
91
+ if (value !== undefined && value !== null && value !== "") {
92
+ url.searchParams.set(key, String(value));
93
+ }
94
+ }
95
+ }
96
+
97
+ export function createApiClient(options) {
98
+ const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl);
99
+ const fetchImpl = requireFetch(options.fetch ?? globalThis.fetch);
100
+ const apiKey = options.apiKey;
101
+
102
+ async function request(method, apiPath, requestOptions = {}) {
103
+ if (!apiKey) {
104
+ throw new HiveApiError("Not logged in. Run hive login first.", { code: "auth_required", status: 401 });
105
+ }
106
+ const url = new URL(`${apiBaseUrl}/${apiPath.replace(/^\/+/, "")}`);
107
+ appendQuery(url, requestOptions.query);
108
+ const headers = {
109
+ Authorization: `Bearer ${apiKey}`,
110
+ ...(requestOptions.body === undefined ? {} : { "Content-Type": "application/json" }),
111
+ ...(requestOptions.idempotencyKey ? { "Idempotency-Key": requestOptions.idempotencyKey } : {}),
112
+ };
113
+ const response = await fetchImpl(url.toString(), {
114
+ body: requestOptions.body === undefined ? undefined : JSON.stringify(requestOptions.body),
115
+ headers,
116
+ method,
117
+ });
118
+ const parsed = await parseJsonResponse(response, url.toString());
119
+ if (!response.ok) {
120
+ throw new HiveApiError(parsed?.error?.message ?? `Hive API request failed with status ${response.status}`, {
121
+ code: parsed?.error?.code,
122
+ requiredScopes: parsed?.error?.requiredScopes,
123
+ status: response.status,
124
+ });
125
+ }
126
+ return parsed;
127
+ }
128
+
129
+ return {
130
+ archiveResource(kind, id) {
131
+ return request("DELETE", `/${kind}/${encodeURIComponent(id)}`);
132
+ },
133
+ cancelAccountDeletion() {
134
+ return request("DELETE", "/account/deletion");
135
+ },
136
+ capabilities() {
137
+ return request("GET", "/capabilities");
138
+ },
139
+ checkHandle(handle) {
140
+ return request("GET", "/profile/handle", { query: { handle } });
141
+ },
142
+ createComment(postId, payload) {
143
+ return request("POST", `/posts/${encodeURIComponent(postId)}/comments`, { body: payload });
144
+ },
145
+ communityMembership(communityId, payload) {
146
+ return request("POST", `/communities/${encodeURIComponent(communityId)}/membership`, { body: payload });
147
+ },
148
+ createResource(kind, payload, idempotencyKey) {
149
+ return request("POST", `/${kind}`, { body: payload, idempotencyKey });
150
+ },
151
+ createUploadUrl(payload) {
152
+ return request("POST", "/uploads/url", { body: payload });
153
+ },
154
+ disconnectLinkedCommunity(communityId) {
155
+ return request("DELETE", `/account/linked-communities/${encodeURIComponent(communityId)}`);
156
+ },
157
+ getAccount() {
158
+ return request("GET", "/account");
159
+ },
160
+ getBuilder(kind) {
161
+ return request("GET", `/profile/${kind}`);
162
+ },
163
+ getProfile() {
164
+ return request("GET", "/profile");
165
+ },
166
+ listResource(kind, query) {
167
+ return request("GET", `/${kind}`, { query });
168
+ },
169
+ listNotificationMutes() {
170
+ return request("GET", "/notification-mutes");
171
+ },
172
+ listNotifications(query) {
173
+ return request("GET", "/notifications", { query });
174
+ },
175
+ listComments(query) {
176
+ return request("GET", "/comments", { query });
177
+ },
178
+ listCommunityApplications(communityId) {
179
+ return request("GET", `/communities/${encodeURIComponent(communityId)}/applications`);
180
+ },
181
+ listCommunityMembers(communityId) {
182
+ return request("GET", `/communities/${encodeURIComponent(communityId)}/members`);
183
+ },
184
+ listWallets() {
185
+ return request("GET", "/wallets");
186
+ },
187
+ markAllNotificationsRead() {
188
+ return request("POST", "/notifications/mark-all-read");
189
+ },
190
+ markNotificationRead(notificationId) {
191
+ return request("POST", `/notifications/${encodeURIComponent(notificationId)}/read`);
192
+ },
193
+ requestAccountDeletion(confirmation) {
194
+ return request("POST", "/account/deletion", { body: { confirmation } });
195
+ },
196
+ requestAccountExport() {
197
+ return request("POST", "/account/export");
198
+ },
199
+ saveBuilder(kind, config) {
200
+ return request("PATCH", `/profile/${kind}`, { body: { config } });
201
+ },
202
+ setDefaultWallet(walletAddress) {
203
+ return request("PATCH", "/wallets/default", { body: { walletAddress } });
204
+ },
205
+ setNftExposure(enabled) {
206
+ return request("PATCH", "/nfts/exposure", { body: { enabled } });
207
+ },
208
+ setNotificationMute(payload) {
209
+ return request("PATCH", "/notification-mutes", { body: payload });
210
+ },
211
+ toggleCommentLike(commentId) {
212
+ return request("POST", `/comments/${encodeURIComponent(commentId)}/like`);
213
+ },
214
+ togglePostLike(postId) {
215
+ return request("POST", `/posts/${encodeURIComponent(postId)}/like`);
216
+ },
217
+ setWalletVisibility(walletAddress, publicallyDiscoverable) {
218
+ return request("PATCH", `/wallets/${encodeURIComponent(walletAddress)}/visibility`, {
219
+ body: { publicallyDiscoverable },
220
+ });
221
+ },
222
+ updateAccountPreferences(payload) {
223
+ return request("PATCH", "/account/preferences", { body: payload });
224
+ },
225
+ updateProfile(payload) {
226
+ return request("PATCH", "/profile", { body: payload });
227
+ },
228
+ updateProfileAccess(payload) {
229
+ return request("PATCH", "/profile/access", { body: payload });
230
+ },
231
+ updateResource(kind, id, payload) {
232
+ return request("PATCH", `/${kind}/${encodeURIComponent(id)}`, { body: payload });
233
+ },
234
+ workflowGet(path, query) {
235
+ return request("GET", `/workflows/${path.replace(/^\/+/, "")}`, { query });
236
+ },
237
+ workflowPatch(path, payload) {
238
+ return request("PATCH", `/workflows/${path.replace(/^\/+/, "")}`, { body: payload });
239
+ },
240
+ workflowPost(path, payload) {
241
+ return request("POST", `/workflows/${path.replace(/^\/+/, "")}`, { body: payload });
242
+ },
243
+ removeNotification(notificationId) {
244
+ return request("DELETE", `/notifications/${encodeURIComponent(notificationId)}`);
245
+ },
246
+ removeComment(commentId) {
247
+ return request("DELETE", `/comments/${encodeURIComponent(commentId)}`);
248
+ },
249
+ removeCommunityMember(communityId, memberPersonId) {
250
+ return request("DELETE", `/communities/${encodeURIComponent(communityId)}/members/${encodeURIComponent(memberPersonId)}`);
251
+ },
252
+ updateComment(commentId, payload) {
253
+ return request("PATCH", `/comments/${encodeURIComponent(commentId)}`, { body: payload });
254
+ },
255
+ reviewCommunityApplication(applicationId, decision) {
256
+ return request("PATCH", `/community-applications/${encodeURIComponent(applicationId)}`, { body: { decision } });
257
+ },
258
+ removeWallet(walletAddress) {
259
+ return request("DELETE", `/wallets/${encodeURIComponent(walletAddress)}`);
260
+ },
261
+ setCommunityRole(communityId, memberPersonId, role) {
262
+ return request("PATCH", `/communities/${encodeURIComponent(communityId)}/members/${encodeURIComponent(memberPersonId)}/role`, {
263
+ body: { role },
264
+ });
265
+ },
266
+ updateCommunityAccess(communityId, payload) {
267
+ return request("PATCH", `/communities/${encodeURIComponent(communityId)}/access`, { body: payload });
268
+ },
269
+ whoami() {
270
+ return request("GET", "/me");
271
+ },
272
+ };
273
+ }