@indigoai-us/hq-cli 5.12.2 → 5.12.3

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,504 @@
1
+ /**
2
+ * Unit tests for `hq files share` (files.ts).
3
+ *
4
+ * Coverage:
5
+ * - parseDuration — pure parser
6
+ * - mintShareSession — happy path + error mapping (401, 403 with path)
7
+ * - formatShareSessionError — status → user copy
8
+ * - registerFilesCommand share action — fork by --with presence:
9
+ * * no --with: calls mint endpoint, prints URL, --no-open suppresses launch
10
+ * * with --with: calls existing direct-grant endpoint, NEVER mints
11
+ * * no paths: prints usage and exits non-zero
12
+ */
13
+
14
+ import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";
15
+
16
+ // Mock the `open` package BEFORE importing files.ts so the action handler
17
+ // resolves to the mock. Returning a resolved promise mirrors open()'s real
18
+ // signature without launching a real browser.
19
+ vi.mock("open", () => ({
20
+ default: vi.fn(() => Promise.resolve({ pid: 0 })),
21
+ }));
22
+
23
+ // `ensureCognitoToken` hits a real keychain/disk path otherwise. Stub it so
24
+ // the action runs without I/O and we can assert pure behavior.
25
+ vi.mock("../utils/cognito-session.js", async (importOriginal) => {
26
+ const original = (await importOriginal()) as Record<string, unknown>;
27
+ return {
28
+ ...original,
29
+ ensureCognitoToken: vi.fn(async () => "test-token"),
30
+ };
31
+ });
32
+
33
+ import { Command } from "commander";
34
+ import open from "open";
35
+ import {
36
+ MAX_SHARE_SESSION_EXPIRY_MS,
37
+ ShareSessionHttpError,
38
+ formatShareSessionError,
39
+ mintShareSession,
40
+ parseDuration,
41
+ registerFilesCommand,
42
+ } from "./files.js";
43
+
44
+ function jsonResponse(status: number, body: unknown): Response {
45
+ return new Response(JSON.stringify(body), {
46
+ status,
47
+ headers: { "Content-Type": "application/json" },
48
+ });
49
+ }
50
+
51
+ let fetchSpy: MockInstance<typeof fetch>;
52
+ let exitSpy: MockInstance<typeof process.exit>;
53
+ let logSpy: MockInstance<typeof console.log>;
54
+ let errSpy: MockInstance<typeof console.error>;
55
+
56
+ beforeEach(() => {
57
+ fetchSpy = vi.spyOn(globalThis, "fetch");
58
+ // process.exit gets thrown so the action's try/catch doesn't keep running
59
+ // after a failure path — mirrors how Commander aborts in real usage.
60
+ exitSpy = vi
61
+ .spyOn(process, "exit")
62
+ .mockImplementation(((code?: number) => {
63
+ throw new Error(`__EXIT__:${code ?? 0}`);
64
+ }) as never);
65
+ logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
66
+ errSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
67
+ });
68
+
69
+ afterEach(() => {
70
+ vi.restoreAllMocks();
71
+ vi.mocked(open).mockClear();
72
+ });
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // parseDuration
76
+ // ---------------------------------------------------------------------------
77
+
78
+ describe("parseDuration", () => {
79
+ it("parses minutes/hours/days into ms", () => {
80
+ expect(parseDuration("15m")).toBe(15 * 60 * 1000);
81
+ expect(parseDuration("1h")).toBe(60 * 60 * 1000);
82
+ expect(parseDuration("24h")).toBe(24 * 60 * 60 * 1000);
83
+ expect(parseDuration("2d")).toBe(2 * 24 * 60 * 60 * 1000);
84
+ });
85
+
86
+ it("returns null for invalid formats", () => {
87
+ expect(parseDuration("15")).toBeNull();
88
+ expect(parseDuration("abc")).toBeNull();
89
+ expect(parseDuration("15s")).toBeNull();
90
+ expect(parseDuration("")).toBeNull();
91
+ });
92
+
93
+ it("agrees with the documented 24h ceiling constant", () => {
94
+ expect(parseDuration("24h")).toBe(MAX_SHARE_SESSION_EXPIRY_MS);
95
+ });
96
+ });
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // mintShareSession
100
+ // ---------------------------------------------------------------------------
101
+
102
+ describe("mintShareSession", () => {
103
+ it("POSTs paths to /files/{companyUid}/share-session and returns the response", async () => {
104
+ fetchSpy.mockResolvedValueOnce(
105
+ jsonResponse(200, {
106
+ url: "https://share.hq/abc",
107
+ token: "tok_share_xyz",
108
+ expiresAt: "2026-05-11T12:00:00Z",
109
+ nonce: "nnnnnn",
110
+ paths: ["docs/", "reports/q1.pdf"],
111
+ maxPermissionByPath: { "docs/": "read", "reports/q1.pdf": "read" },
112
+ }),
113
+ );
114
+
115
+ const session = await mintShareSession({
116
+ token: "test-token",
117
+ companyUid: "cmp_acme",
118
+ paths: ["docs/", "reports/q1.pdf"],
119
+ });
120
+
121
+ expect(session.url).toBe("https://share.hq/abc");
122
+ expect(session.expiresAt).toBe("2026-05-11T12:00:00Z");
123
+
124
+ const call = fetchSpy.mock.calls[0];
125
+ expect(String(call[0])).toMatch(/\/files\/cmp_acme\/share-session$/);
126
+ expect(call[1]?.method).toBe("POST");
127
+ const body = JSON.parse((call[1]?.body as string) ?? "{}");
128
+ expect(body).toEqual({ paths: ["docs/", "reports/q1.pdf"] });
129
+ });
130
+
131
+ it("includes expiresInMs only when supplied", async () => {
132
+ fetchSpy.mockResolvedValueOnce(
133
+ jsonResponse(200, { url: "https://share.hq/x", expiresAt: "now" }),
134
+ );
135
+
136
+ await mintShareSession({
137
+ token: "test-token",
138
+ companyUid: "cmp_acme",
139
+ paths: ["foo"],
140
+ expiresInMs: 15 * 60 * 1000,
141
+ });
142
+
143
+ const body = JSON.parse(
144
+ (fetchSpy.mock.calls[0][1]?.body as string) ?? "{}",
145
+ );
146
+ expect(body).toEqual({ paths: ["foo"], expiresInMs: 15 * 60 * 1000 });
147
+ });
148
+
149
+ it("throws ShareSessionHttpError on 401", async () => {
150
+ fetchSpy.mockResolvedValueOnce(jsonResponse(401, { error: "unauth" }));
151
+ await expect(
152
+ mintShareSession({
153
+ token: "bad",
154
+ companyUid: "cmp_acme",
155
+ paths: ["foo"],
156
+ }),
157
+ ).rejects.toBeInstanceOf(ShareSessionHttpError);
158
+ });
159
+
160
+ it("propagates the offending path on 403 forbidden-per-path", async () => {
161
+ fetchSpy.mockResolvedValueOnce(
162
+ jsonResponse(403, { error: "forbidden", path: "secrets/" }),
163
+ );
164
+ try {
165
+ await mintShareSession({
166
+ token: "test-token",
167
+ companyUid: "cmp_acme",
168
+ paths: ["secrets/"],
169
+ });
170
+ expect.fail("should have thrown");
171
+ } catch (err) {
172
+ expect(err).toBeInstanceOf(ShareSessionHttpError);
173
+ expect((err as ShareSessionHttpError).status).toBe(403);
174
+ expect((err as ShareSessionHttpError).path).toBe("secrets/");
175
+ }
176
+ });
177
+ });
178
+
179
+ // ---------------------------------------------------------------------------
180
+ // formatShareSessionError
181
+ // ---------------------------------------------------------------------------
182
+
183
+ describe("formatShareSessionError", () => {
184
+ it("maps 401 to a login hint", () => {
185
+ expect(
186
+ formatShareSessionError(new ShareSessionHttpError(401, "unauth")),
187
+ ).toMatch(/run `hq login`/);
188
+ });
189
+
190
+ it("maps 403 with a path to a per-path message", () => {
191
+ const err = new ShareSessionHttpError(403, "forbidden", "secrets/");
192
+ expect(formatShareSessionError(err)).toMatch(/'secrets\/'/);
193
+ });
194
+
195
+ it("maps 403 without a path to a generic membership hint", () => {
196
+ expect(
197
+ formatShareSessionError(new ShareSessionHttpError(403, "forbidden")),
198
+ ).toMatch(/company member/);
199
+ });
200
+
201
+ it("prefixes 5xx with 'Server error:'", () => {
202
+ expect(
203
+ formatShareSessionError(new ShareSessionHttpError(500, "boom")),
204
+ ).toMatch(/^Server error: boom/);
205
+ });
206
+
207
+ it("falls through to the message for unmapped statuses", () => {
208
+ expect(
209
+ formatShareSessionError(new ShareSessionHttpError(418, "tea")),
210
+ ).toMatch(/tea/);
211
+ });
212
+ });
213
+
214
+ // ---------------------------------------------------------------------------
215
+ // Command action — share fork: no --with → mint, with --with → direct grant
216
+ // ---------------------------------------------------------------------------
217
+
218
+ /** Build a fresh program + register `files` so each test gets a clean parser. */
219
+ function buildProgram(): Command {
220
+ const program = new Command();
221
+ // exitOverride keeps Commander from killing the process on parse errors —
222
+ // we want any failure to surface as a thrown error or a process.exit spy.
223
+ program.exitOverride();
224
+ registerFilesCommand(program);
225
+ return program;
226
+ }
227
+
228
+ describe("hq files share — browser-launch fork (no --with)", () => {
229
+ it("PRD scenario 1: --no-open prints URL, exits 0, does not call open()", async () => {
230
+ // 1) /membership/me — used by getCompanyUid fallback
231
+ fetchSpy.mockResolvedValueOnce(
232
+ jsonResponse(200, {
233
+ memberships: [
234
+ {
235
+ membershipKey: "k1",
236
+ companyUid: "cmp_acme",
237
+ role: "member",
238
+ status: "active",
239
+ },
240
+ ],
241
+ }),
242
+ );
243
+ // 2) POST /files/cmp_acme/share-session
244
+ fetchSpy.mockResolvedValueOnce(
245
+ jsonResponse(200, {
246
+ url: "https://share.hq/fixture-url",
247
+ expiresAt: "2026-05-11T13:00:00Z",
248
+ }),
249
+ );
250
+
251
+ const program = buildProgram();
252
+ await program.parseAsync(
253
+ ["files", "share", "fooPath", "--no-open"],
254
+ { from: "user" },
255
+ );
256
+
257
+ // Mint endpoint was called, with the right body.
258
+ const mintCall = fetchSpy.mock.calls.find((c) =>
259
+ String(c[0]).includes("/share-session"),
260
+ );
261
+ expect(mintCall).toBeDefined();
262
+ const body = JSON.parse((mintCall![1]?.body as string) ?? "{}");
263
+ expect(body).toEqual({ paths: ["fooPath"] });
264
+
265
+ // URL printed to stdout.
266
+ const printed = logSpy.mock.calls.map((c) => String(c[0])).join("\n");
267
+ expect(printed).toContain("https://share.hq/fixture-url");
268
+
269
+ // Browser was NOT launched.
270
+ expect(open).not.toHaveBeenCalled();
271
+
272
+ // No process.exit on the success path.
273
+ expect(exitSpy).not.toHaveBeenCalled();
274
+ });
275
+
276
+ it("forwards --expires as ms to the mint endpoint", async () => {
277
+ fetchSpy.mockResolvedValueOnce(
278
+ jsonResponse(200, {
279
+ memberships: [
280
+ {
281
+ membershipKey: "k1",
282
+ companyUid: "cmp_acme",
283
+ role: "member",
284
+ status: "active",
285
+ },
286
+ ],
287
+ }),
288
+ );
289
+ fetchSpy.mockResolvedValueOnce(
290
+ jsonResponse(200, {
291
+ url: "https://share.hq/x",
292
+ expiresAt: "2026-05-11T13:00:00Z",
293
+ }),
294
+ );
295
+
296
+ const program = buildProgram();
297
+ await program.parseAsync(
298
+ ["files", "share", "foo", "--expires", "1h", "--no-open"],
299
+ { from: "user" },
300
+ );
301
+
302
+ const mintCall = fetchSpy.mock.calls.find((c) =>
303
+ String(c[0]).includes("/share-session"),
304
+ )!;
305
+ const body = JSON.parse((mintCall[1]?.body as string) ?? "{}");
306
+ expect(body).toEqual({ paths: ["foo"], expiresInMs: 60 * 60 * 1000 });
307
+ });
308
+
309
+ it("rejects --expires beyond the 24h CLI ceiling", async () => {
310
+ const program = buildProgram();
311
+ await expect(
312
+ program.parseAsync(
313
+ ["files", "share", "foo", "--expires", "2d", "--no-open"],
314
+ { from: "user" },
315
+ ),
316
+ ).rejects.toThrow(/__EXIT__:1/);
317
+
318
+ const errs = errSpy.mock.calls.map((c) => String(c[0])).join("\n");
319
+ expect(errs).toMatch(/Maximum share-session expiry is 24h/);
320
+ // No fetch should have happened — pre-validation rejected early.
321
+ expect(fetchSpy).not.toHaveBeenCalled();
322
+ });
323
+
324
+ it("prints a usage message when no paths are supplied", async () => {
325
+ const program = buildProgram();
326
+ await expect(
327
+ program.parseAsync(["files", "share"], { from: "user" }),
328
+ ).rejects.toThrow(/__EXIT__:1/);
329
+
330
+ const errs = errSpy.mock.calls.map((c) => String(c[0])).join("\n");
331
+ expect(errs).toMatch(/usage: hq files share <paths\.\.\.>/);
332
+ expect(fetchSpy).not.toHaveBeenCalled();
333
+ });
334
+
335
+ it("surfaces a 401 from the mint endpoint as an actionable error", async () => {
336
+ fetchSpy.mockResolvedValueOnce(
337
+ jsonResponse(200, {
338
+ memberships: [
339
+ {
340
+ membershipKey: "k1",
341
+ companyUid: "cmp_acme",
342
+ role: "member",
343
+ status: "active",
344
+ },
345
+ ],
346
+ }),
347
+ );
348
+ fetchSpy.mockResolvedValueOnce(jsonResponse(401, { error: "unauth" }));
349
+
350
+ const program = buildProgram();
351
+ await expect(
352
+ program.parseAsync(
353
+ ["files", "share", "foo", "--no-open"],
354
+ { from: "user" },
355
+ ),
356
+ ).rejects.toThrow(/__EXIT__:1/);
357
+
358
+ const errs = errSpy.mock.calls.map((c) => String(c[0])).join("\n");
359
+ expect(errs).toMatch(/run `hq login`/);
360
+ });
361
+ });
362
+
363
+ describe("hq files share — direct-grant fork (with --with)", () => {
364
+ it("PRD scenario 2: --with email --permission read writes a direct grant and never calls the mint endpoint", async () => {
365
+ // 1) /membership/me for company resolution
366
+ fetchSpy.mockResolvedValueOnce(
367
+ jsonResponse(200, {
368
+ memberships: [
369
+ {
370
+ membershipKey: "k1",
371
+ companyUid: "cmp_acme",
372
+ role: "member",
373
+ status: "active",
374
+ },
375
+ ],
376
+ }),
377
+ );
378
+ // 2) POST /files/cmp_acme/acl/grant
379
+ fetchSpy.mockResolvedValueOnce(
380
+ jsonResponse(200, { acl: { path: "fooPath" } }),
381
+ );
382
+
383
+ const program = buildProgram();
384
+ await program.parseAsync(
385
+ [
386
+ "files",
387
+ "share",
388
+ "fooPath",
389
+ "--with",
390
+ "user@example.com",
391
+ "--permission",
392
+ "read",
393
+ ],
394
+ { from: "user" },
395
+ );
396
+
397
+ // The mint endpoint MUST NOT have been called.
398
+ const mintCalls = fetchSpy.mock.calls.filter((c) =>
399
+ String(c[0]).includes("/share-session"),
400
+ );
401
+ expect(mintCalls).toHaveLength(0);
402
+
403
+ // The grant endpoint WAS called with the right body.
404
+ const grantCall = fetchSpy.mock.calls.find((c) =>
405
+ String(c[0]).includes("/acl/grant"),
406
+ );
407
+ expect(grantCall).toBeDefined();
408
+ const body = JSON.parse((grantCall![1]?.body as string) ?? "{}");
409
+ expect(body).toEqual({
410
+ prefix: "fooPath",
411
+ granteeType: "email",
412
+ granteeId: "user@example.com",
413
+ permission: "read",
414
+ });
415
+
416
+ // Browser must not have launched in the direct-grant flow.
417
+ expect(open).not.toHaveBeenCalled();
418
+ });
419
+
420
+ it("rejects multiple paths when --with is set", async () => {
421
+ const program = buildProgram();
422
+ await expect(
423
+ program.parseAsync(
424
+ [
425
+ "files",
426
+ "share",
427
+ "a",
428
+ "b",
429
+ "--with",
430
+ "user@example.com",
431
+ "--permission",
432
+ "read",
433
+ ],
434
+ { from: "user" },
435
+ ),
436
+ ).rejects.toThrow(/__EXIT__:1/);
437
+
438
+ const errs = errSpy.mock.calls.map((c) => String(c[0])).join("\n");
439
+ expect(errs).toMatch(/exactly one prefix/);
440
+ expect(fetchSpy).not.toHaveBeenCalled();
441
+ });
442
+
443
+ it("US-001 regression: --with @all writes a company-wide grant (granteeType:'company-wide', granteeId:'')", async () => {
444
+ // 1) /membership/me for company resolution
445
+ fetchSpy.mockResolvedValueOnce(
446
+ jsonResponse(200, {
447
+ memberships: [
448
+ {
449
+ membershipKey: "k1",
450
+ companyUid: "cmp_acme",
451
+ role: "member",
452
+ status: "active",
453
+ },
454
+ ],
455
+ }),
456
+ );
457
+ // 2) POST /files/cmp_acme/acl/grant
458
+ fetchSpy.mockResolvedValueOnce(
459
+ jsonResponse(200, { acl: { path: "fooPath" } }),
460
+ );
461
+
462
+ const program = buildProgram();
463
+ await program.parseAsync(
464
+ ["files", "share", "fooPath", "--with", "@all", "--permission", "write"],
465
+ { from: "user" },
466
+ );
467
+
468
+ // Mint endpoint MUST NOT have been called — direct-grant fork only.
469
+ const mintCalls = fetchSpy.mock.calls.filter((c) =>
470
+ String(c[0]).includes("/share-session"),
471
+ );
472
+ expect(mintCalls).toHaveLength(0);
473
+
474
+ // Grant endpoint received a company-wide entry per US-001.
475
+ const grantCall = fetchSpy.mock.calls.find((c) =>
476
+ String(c[0]).includes("/acl/grant"),
477
+ );
478
+ expect(grantCall).toBeDefined();
479
+ const body = JSON.parse((grantCall![1]?.body as string) ?? "{}");
480
+ expect(body).toEqual({
481
+ prefix: "fooPath",
482
+ granteeType: "company-wide",
483
+ granteeId: "",
484
+ permission: "write",
485
+ });
486
+
487
+ // Browser must not have launched in the direct-grant flow.
488
+ expect(open).not.toHaveBeenCalled();
489
+ });
490
+
491
+ it("rejects --with without --permission", async () => {
492
+ const program = buildProgram();
493
+ await expect(
494
+ program.parseAsync(
495
+ ["files", "share", "foo", "--with", "user@example.com"],
496
+ { from: "user" },
497
+ ),
498
+ ).rejects.toThrow(/__EXIT__:1/);
499
+
500
+ const errs = errSpy.mock.calls.map((c) => String(c[0])).join("\n");
501
+ expect(errs).toMatch(/--permission is required/);
502
+ expect(fetchSpy).not.toHaveBeenCalled();
503
+ });
504
+ });