@indigoai-us/hq-cli 5.32.0 → 5.33.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,444 @@
1
+ /**
2
+ * safe-extract — hardened tarball extraction for the content-pack installer.
3
+ *
4
+ * THREAT MODEL (US-020). A pack tarball is UNTRUSTED input fetched from npm,
5
+ * a git remote, or a local path the user merely pointed at. Naively shelling
6
+ * out to `tar -xzf <tarball> -C <dir>` trusts the archive to behave; a hostile
7
+ * archive can:
8
+ *
9
+ * 1. Path traversal / "zip slip": an entry named `../../etc/cron.d/evil` or
10
+ * an absolute `/etc/passwd` escapes the intended target dir and clobbers
11
+ * arbitrary files (RCE if it lands a hook / cron / shell-rc).
12
+ * 2. Symlink/hardlink escape: an entry that is a symlink whose target points
13
+ * OUTSIDE the pack dir (e.g. `link -> /etc`), optionally followed by a
14
+ * second entry that writes "through" the link — the classic two-step
15
+ * tar symlink attack.
16
+ * 3. Decompression bomb: a tiny `.tgz` that inflates to terabytes (many
17
+ * files, or one enormous sparse/zero file), exhausting disk or memory.
18
+ *
19
+ * DEFENSE (defense-in-depth, default-deny):
20
+ * - PRE-FLIGHT: enumerate every entry's header (type, size, name, link
21
+ * target) via `tar -tv` WITHOUT extracting. Reject the whole archive if
22
+ * ANY entry fails a containment or cap check. Containment uses normalized
23
+ * path-prefix logic on the *resolved* path, never naive string matching.
24
+ * - CAPS: enforced against the header-reported uncompressed sizes during the
25
+ * pre-flight scan, so we abort BEFORE writing a single byte of a bomb.
26
+ * - STAGED + ATOMIC: extraction lands in a sibling staging dir on the SAME
27
+ * filesystem as the final destination; only after a successful, fully
28
+ * validated extract do we `fs.rename` it into place (atomic). Any failure
29
+ * mid-extract rolls the staging dir back entirely (`rm -rf` in finally) —
30
+ * no partial/half-wired pack is ever left behind.
31
+ * - POST-EXTRACT: an independent realpath containment sweep over everything
32
+ * actually written (we do NOT rely solely on the pre-flight scan or on the
33
+ * tar binary's own protections).
34
+ */
35
+
36
+ import { execFileSync } from 'child_process';
37
+ import * as fs from 'fs';
38
+ import * as path from 'path';
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Caps (decompression-bomb guard). Named constants with documented defaults.
42
+ // Overridable per-call so tests can trip the tripwire cheaply (and so US-024's
43
+ // adversarial suite can reuse low caps without building literal multi-GB
44
+ // fixtures).
45
+ // ---------------------------------------------------------------------------
46
+
47
+ export interface ExtractCaps {
48
+ /** Max total uncompressed bytes across all entries. Default 256 MiB. */
49
+ maxUncompressedBytes: number;
50
+ /** Max number of entries in the archive. Default 20,000. */
51
+ maxFileCount: number;
52
+ /** Max uncompressed bytes of any single entry. Default 64 MiB. */
53
+ maxSingleFileBytes: number;
54
+ }
55
+
56
+ export const DEFAULT_CAPS: ExtractCaps = {
57
+ // A content pack is docs/skills/policies/small scripts. 256 MiB is already
58
+ // generous; anything larger is almost certainly a bomb or a mistake.
59
+ maxUncompressedBytes: 256 * 1024 * 1024,
60
+ maxFileCount: 20_000,
61
+ maxSingleFileBytes: 64 * 1024 * 1024,
62
+ };
63
+
64
+ export class UnsafeArchiveError extends Error {
65
+ constructor(message: string) {
66
+ super(message);
67
+ this.name = 'UnsafeArchiveError';
68
+ }
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Entry-header model + tar listing parser
73
+ // ---------------------------------------------------------------------------
74
+
75
+ export type EntryType = 'file' | 'dir' | 'symlink' | 'hardlink' | 'other';
76
+
77
+ export interface TarEntry {
78
+ type: EntryType;
79
+ /** Entry path as recorded in the archive (may contain `..`, be absolute…). */
80
+ name: string;
81
+ /** Uncompressed size in bytes from the header (0 for dirs/links). */
82
+ size: number;
83
+ /** For sym/hardlinks: the link target as recorded in the archive. */
84
+ linkTarget?: string;
85
+ }
86
+
87
+ /**
88
+ * Parse the verbose listing produced by `tar -tv`. We use the verbose form so
89
+ * we get the type flag, size, and (for links) the `name -> target` /
90
+ * `name link to target` suffix without extracting anything.
91
+ *
92
+ * SECURITY-CRITICAL CROSS-PLATFORM NOTE. bsdtar (macOS/BSD) and GNU tar
93
+ * (Linux / prod Lambdas) format the verbose listing DIFFERENTLY, and an
94
+ * implementation that only understands one of them silently parses ZERO
95
+ * entries against the other — which means the pre-flight containment scan
96
+ * sees nothing to reject and every malicious archive sails through. The two
97
+ * shapes we must both handle:
98
+ *
99
+ * bsdtar: <mode> <links> <owner> <group> <size> <Mon> <DD> <HH:MM|YYYY> <name...>
100
+ * -rw-r--r-- 0 user group 1234 Jan 1 00:00 path/file
101
+ * lrwxr-xr-x 0 user group 0 Jan 1 00:00 link -> target
102
+ *
103
+ * GNU: <mode> <owner>/<group> <size> <YYYY-MM-DD> <HH:MM[:SS]> <name...>
104
+ * -rw-r--r-- user/group 1234 2026-01-01 00:00 path/file
105
+ * lrwxrwxrwx user/group 0 2026-01-01 00:00 link -> target
106
+ * hrw-r--r-- user/group 0 2026-01-01 00:00 hard link to target
107
+ *
108
+ * GNU has NO link-count column, joins owner/group with `/`, and renders the
109
+ * date ISO-style (`YYYY-MM-DD HH:MM`) instead of `Mon DD HH:MM`. The previous
110
+ * parser anchored on a `[A-Za-z]{3}` month token, so it matched NOTHING under
111
+ * GNU tar and returned [] — the cross-platform hole this fix closes.
112
+ *
113
+ * Robust strategy: do NOT anchor on the (format-divergent) date column. Anchor
114
+ * on the leading mode string (always present, position 0, stable type char),
115
+ * then take the SIZE as the last integer that appears before the date/time
116
+ * column, accepting BOTH date formats. The leading mode char is the type flag:
117
+ * '-' file, 'd' dir, 'l' symlink, 'h' hardlink (GNU prints 'h'); bsdtar
118
+ * prints hardlinks as files with a "link to" suffix, which we also detect.
119
+ */
120
+ export function parseTarListing(verbose: string): TarEntry[] {
121
+ const entries: TarEntry[] = [];
122
+ for (const raw of verbose.split('\n')) {
123
+ const line = raw.replace(/\r$/, '');
124
+ if (line.trim() === '') continue;
125
+ const modeChar = line[0];
126
+ // Only accept lines that actually begin with a tar mode string (10 chars:
127
+ // a type flag followed by 9 permission chars, possibly with a trailing
128
+ // ACL/xattr '+'/'@'/'.'). This skips non-entry noise without depending on
129
+ // the date column at all.
130
+ if (!/^[-dlhpscbD][-rwxXsStT]{9}[.+@]?\s/.test(line)) continue;
131
+
132
+ // The size is the last run of digits that sits immediately before the
133
+ // date/time column. We accept BOTH date renderings:
134
+ // bsdtar: `Mon DD HH:MM` / `Mon DD YYYY`
135
+ // GNU: `YYYY-MM-DD HH:MM[:SS]`
136
+ // Anchoring the size on "the integer right before a recognized date" works
137
+ // identically whether or not a link-count column is present (bsdtar) and
138
+ // whether owner/group is one slash-joined token (GNU) or two columns
139
+ // (bsdtar), because we only ever look at the integer adjacent to the date.
140
+ const dateRe =
141
+ /\s(\d+)\s+(?:[A-Za-z]{3}\s+\d{1,2}\s+(?:\d{1,2}:\d{2}|\d{4})|\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}(?::\d{2})?)\s+/;
142
+ const m = dateRe.exec(line);
143
+ if (!m) continue;
144
+ const size = Number.parseInt(m[1], 10);
145
+ const nameAndLink = line.slice(m.index + m[0].length).trim();
146
+
147
+ let type: EntryType;
148
+ let name = nameAndLink;
149
+ let linkTarget: string | undefined;
150
+
151
+ if (modeChar === 'd') {
152
+ type = 'dir';
153
+ name = name.replace(/\/+$/, '');
154
+ } else if (modeChar === 'l') {
155
+ type = 'symlink';
156
+ const arrow = nameAndLink.indexOf(' -> ');
157
+ if (arrow >= 0) {
158
+ name = nameAndLink.slice(0, arrow);
159
+ linkTarget = nameAndLink.slice(arrow + 4);
160
+ }
161
+ } else if (modeChar === 'h') {
162
+ type = 'hardlink';
163
+ // GNU: "name link to target"
164
+ const m = / link to /.exec(nameAndLink);
165
+ if (m) {
166
+ name = nameAndLink.slice(0, m.index);
167
+ linkTarget = nameAndLink.slice(m.index + m[0].length);
168
+ }
169
+ } else if (modeChar === '-') {
170
+ // bsdtar renders hardlinks as a file entry with a trailing "link to".
171
+ const m = / link to /.exec(nameAndLink);
172
+ if (m) {
173
+ type = 'hardlink';
174
+ name = nameAndLink.slice(0, m.index);
175
+ linkTarget = nameAndLink.slice(m.index + m[0].length);
176
+ } else {
177
+ type = 'file';
178
+ }
179
+ } else {
180
+ type = 'other';
181
+ }
182
+
183
+ entries.push({
184
+ type,
185
+ name,
186
+ size: Number.isFinite(size) ? size : 0,
187
+ linkTarget,
188
+ });
189
+ }
190
+ return entries;
191
+ }
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // Containment — normalized prefix on the RESOLVED path (not string matching)
195
+ // ---------------------------------------------------------------------------
196
+
197
+ /**
198
+ * True iff `candidate` is `base` itself or strictly nested under it, judged on
199
+ * normalized absolute paths with a trailing-separator guard so that a sibling
200
+ * like `/a/baseEVIL` is NOT considered "under" `/a/base`.
201
+ */
202
+ export function isContained(base: string, candidate: string): boolean {
203
+ const b = path.resolve(base);
204
+ const c = path.resolve(candidate);
205
+ if (c === b) return true;
206
+ const withSep = b.endsWith(path.sep) ? b : b + path.sep;
207
+ return c.startsWith(withSep);
208
+ }
209
+
210
+ /**
211
+ * Resolve where an entry NAME would land under `targetDir` and assert it stays
212
+ * inside. Rejects absolute names and any `..` that escapes. Returns the
213
+ * resolved absolute path on success.
214
+ */
215
+ export function resolveContainedPath(targetDir: string, entryName: string): string {
216
+ // path.resolve collapses `..` segments and makes absolute names absolute to
217
+ // the FS root (so `/etc/passwd` resolves to itself, which then fails
218
+ // containment) — exactly what we want for the check.
219
+ const resolved = path.resolve(targetDir, entryName);
220
+ if (!isContained(targetDir, resolved)) {
221
+ throw new UnsafeArchiveError(
222
+ `Path traversal blocked: entry "${entryName}" resolves to "${resolved}", ` +
223
+ `outside extraction dir "${path.resolve(targetDir)}".`,
224
+ );
225
+ }
226
+ return resolved;
227
+ }
228
+
229
+ /**
230
+ * Validate a sym/hardlink's target stays inside `packDir`. The link is created
231
+ * AT `entryAbs` (already known-contained), so a relative target is resolved
232
+ * against the link's parent dir; an absolute target is checked as-is. Either
233
+ * way the final location must be contained in the pack dir.
234
+ */
235
+ export function assertLinkTargetContained(
236
+ packDir: string,
237
+ entryAbs: string,
238
+ linkTarget: string,
239
+ ): void {
240
+ const resolvedTarget = path.isAbsolute(linkTarget)
241
+ ? path.resolve(linkTarget)
242
+ : path.resolve(path.dirname(entryAbs), linkTarget);
243
+ if (!isContained(packDir, resolvedTarget)) {
244
+ throw new UnsafeArchiveError(
245
+ `Link escape blocked: entry "${path.relative(packDir, entryAbs)}" points to ` +
246
+ `"${linkTarget}" -> "${resolvedTarget}", outside pack dir "${path.resolve(packDir)}".`,
247
+ );
248
+ }
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Pre-flight: list entries, enforce containment + caps WITHOUT extracting
253
+ // ---------------------------------------------------------------------------
254
+
255
+ /**
256
+ * List a gzip-compressed tarball's entries via `tar -tvf` (no extraction).
257
+ * argv form — never a shell string — so a hostile filename can't break out.
258
+ */
259
+ export function listTarball(tarballPath: string): TarEntry[] {
260
+ const out = execFileSync('tar', ['-tvf', tarballPath], {
261
+ encoding: 'utf-8',
262
+ maxBuffer: 64 * 1024 * 1024,
263
+ stdio: ['ignore', 'pipe', 'pipe'],
264
+ });
265
+ return parseTarListing(out);
266
+ }
267
+
268
+ /**
269
+ * Pre-flight validation against the entry headers. Enforces (a) containment of
270
+ * every entry name under `targetDir`, (b) containment of every link target
271
+ * under `targetDir`, and (c) the three decompression-bomb caps. Throws
272
+ * UnsafeArchiveError on the first violation — default-deny.
273
+ */
274
+ export function validateEntries(
275
+ entries: TarEntry[],
276
+ targetDir: string,
277
+ caps: ExtractCaps = DEFAULT_CAPS,
278
+ ): void {
279
+ // Count real members (dirs included — they still occupy inodes; cheap to
280
+ // count and keeps "many empty dirs" bombs in scope).
281
+ if (entries.length > caps.maxFileCount) {
282
+ throw new UnsafeArchiveError(
283
+ `Decompression-bomb guard: archive has ${entries.length} entries, ` +
284
+ `exceeding the limit of ${caps.maxFileCount}.`,
285
+ );
286
+ }
287
+
288
+ let total = 0;
289
+ for (const e of entries) {
290
+ if (e.type === 'other') {
291
+ throw new UnsafeArchiveError(
292
+ `Unsupported entry type for "${e.name}" — only files, dirs, and ` +
293
+ `contained links are allowed.`,
294
+ );
295
+ }
296
+
297
+ // (a) name containment — rejects `..` traversal and absolute paths.
298
+ const entryAbs = resolveContainedPath(targetDir, e.name);
299
+
300
+ // (b) link-target containment.
301
+ if ((e.type === 'symlink' || e.type === 'hardlink') && e.linkTarget) {
302
+ assertLinkTargetContained(targetDir, entryAbs, e.linkTarget);
303
+ }
304
+
305
+ // (c) per-file + cumulative caps.
306
+ if (e.size > caps.maxSingleFileBytes) {
307
+ throw new UnsafeArchiveError(
308
+ `Decompression-bomb guard: entry "${e.name}" is ${e.size} bytes, ` +
309
+ `exceeding the per-file limit of ${caps.maxSingleFileBytes}.`,
310
+ );
311
+ }
312
+ total += e.size;
313
+ if (total > caps.maxUncompressedBytes) {
314
+ throw new UnsafeArchiveError(
315
+ `Decompression-bomb guard: cumulative uncompressed size exceeded ` +
316
+ `${caps.maxUncompressedBytes} bytes (reached ${total} before finishing the scan).`,
317
+ );
318
+ }
319
+ }
320
+ }
321
+
322
+ // ---------------------------------------------------------------------------
323
+ // Post-extract: independent realpath containment sweep
324
+ // ---------------------------------------------------------------------------
325
+
326
+ /**
327
+ * Walk everything actually written under `stagingDir` and assert that no entry
328
+ * — and, for symlinks, no link target — escapes. This is the defense-in-depth
329
+ * backstop: it does not trust the pre-flight scan OR the tar binary. Uses
330
+ * realpath on the link's PARENT (which exists) plus lstat to inspect links
331
+ * without following them off-tree.
332
+ */
333
+ export function assertExtractContained(stagingDir: string): void {
334
+ const realRoot = fs.realpathSync(stagingDir);
335
+ const walk = (dir: string): void => {
336
+ for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
337
+ const abs = path.join(dir, dirent.name);
338
+ if (dirent.isSymbolicLink()) {
339
+ const target = fs.readlinkSync(abs);
340
+ const resolved = path.isAbsolute(target)
341
+ ? path.resolve(target)
342
+ : path.resolve(path.dirname(abs), target);
343
+ if (!isContained(realRoot, resolved)) {
344
+ throw new UnsafeArchiveError(
345
+ `Post-extract link escape: "${path.relative(realRoot, abs)}" -> "${target}".`,
346
+ );
347
+ }
348
+ continue; // do not descend through links
349
+ }
350
+ // Real path of the entry's parent must stay inside the root (catches a
351
+ // dir that is itself a link off-tree, belt-and-suspenders).
352
+ const realParent = fs.realpathSync(path.dirname(abs));
353
+ if (!isContained(realRoot, path.join(realParent, dirent.name))) {
354
+ throw new UnsafeArchiveError(
355
+ `Post-extract path escape: "${abs}" resolves outside "${realRoot}".`,
356
+ );
357
+ }
358
+ if (dirent.isDirectory()) walk(abs);
359
+ }
360
+ };
361
+ walk(realRoot);
362
+ }
363
+
364
+ // ---------------------------------------------------------------------------
365
+ // Public: staged + atomic safe extraction
366
+ // ---------------------------------------------------------------------------
367
+
368
+ export interface SafeExtractOptions {
369
+ caps?: ExtractCaps;
370
+ /**
371
+ * Test seam: invoked AFTER `tar` extracts into the staging dir but BEFORE
372
+ * the post-extract sweep / atomic rename. Throwing here simulates a failure
373
+ * "mid-extract" and must leave NO staging or final dir behind.
374
+ */
375
+ afterExtractHook?: (stagingDir: string) => void;
376
+ }
377
+
378
+ /**
379
+ * Safely extract `tarballPath` so its contents land atomically at `finalDir`.
380
+ *
381
+ * Sequence:
382
+ * 1. Pre-flight list + validate (containment + caps) — abort before writing.
383
+ * 2. Extract into a sibling `*.staging-<rand>` dir on the SAME filesystem.
384
+ * 3. Post-extract realpath containment sweep (independent backstop).
385
+ * 4. `afterExtractHook` (test failure-injection seam).
386
+ * 5. Atomic `fs.rename(staging -> finalDir)`.
387
+ * 6. finally: `rm -rf` the staging dir if it still exists (rollback).
388
+ *
389
+ * On ANY failure the staging dir is removed and `finalDir` is never created,
390
+ * so a half-extracted pack can never be wired.
391
+ */
392
+ export function safeExtractTarball(
393
+ tarballPath: string,
394
+ finalDir: string,
395
+ opts: SafeExtractOptions = {},
396
+ ): void {
397
+ const caps = opts.caps ?? DEFAULT_CAPS;
398
+
399
+ if (fs.existsSync(finalDir)) {
400
+ throw new Error(
401
+ `safeExtractTarball: refusing to extract over existing dir "${finalDir}".`,
402
+ );
403
+ }
404
+
405
+ // 1. Pre-flight against headers (no bytes written yet).
406
+ const entries = listTarball(tarballPath);
407
+ validateEntries(entries, finalDir, caps);
408
+
409
+ // 2. Sibling staging dir on the same filesystem so the rename is atomic.
410
+ const parent = path.dirname(path.resolve(finalDir));
411
+ fs.mkdirSync(parent, { recursive: true });
412
+ const stagingDir = fs.mkdtempSync(
413
+ path.join(parent, `.${path.basename(finalDir)}.staging-`),
414
+ );
415
+
416
+ try {
417
+ // `--no-same-owner` avoids chown surprises when run as root; argv form, no
418
+ // shell. We deliberately re-extract here (not the pre-flight listing) and
419
+ // re-validate after, rather than trusting tar to honor any single flag.
420
+ execFileSync(
421
+ 'tar',
422
+ ['-xzf', tarballPath, '-C', stagingDir, '--no-same-owner'],
423
+ { stdio: 'inherit' },
424
+ );
425
+
426
+ // 3. Independent backstop sweep over what actually landed.
427
+ assertExtractContained(stagingDir);
428
+
429
+ // 4. Failure-injection seam (tests).
430
+ opts.afterExtractHook?.(stagingDir);
431
+
432
+ // 5. Atomic commit. `fs.renameSync` is atomic within a filesystem; the
433
+ // staged contents are fully present and validated before this point, so
434
+ // the live location only ever sees a complete pack — never a partial.
435
+ fs.renameSync(stagingDir, finalDir);
436
+ } finally {
437
+ // Rollback: if anything before the rename threw, the staging dir still
438
+ // exists and is removed here — no partial/half-wired pack survives. After a
439
+ // successful rename the staging dir is gone, so this is a no-op.
440
+ if (fs.existsSync(stagingDir)) {
441
+ fs.rmSync(stagingDir, { recursive: true, force: true });
442
+ }
443
+ }
444
+ }
package/src/index.ts CHANGED
@@ -24,6 +24,7 @@ import { registerPackageRemoveCommand } from "./commands/pkg-remove.js";
24
24
  import { registerPackageUpdateCommand } from "./commands/pkg-update.js";
25
25
  import { registerPackageListCommand } from "./commands/pkg-list.js";
26
26
  import { registerPacksCommand } from "./commands/packs.js";
27
+ import { registerPublishCommand } from "./commands/publish.js";
27
28
  import { registerTeamSyncCommand } from "./commands/team-sync.js";
28
29
  import { registerAuthCommands } from "./commands/auth.js";
29
30
  import { registerSecretsCommand } from "./commands/secrets.js";
@@ -101,6 +102,11 @@ registerPacksCommand(program);
101
102
  registerPackageInstallCommand(program);
102
103
  registerPackageRemoveCommand(program);
103
104
 
105
+ // Marketplace publish (top-level — packer + authenticated upload, US-004)
106
+ // "hq publish <skill-or-worker-path>" packages and submits a pack to the
107
+ // marketplace via POST /v1/listings.
108
+ registerPublishCommand(program);
109
+
104
110
  // Cloud sync subcommand group
105
111
  const syncCmd = program
106
112
  .command("sync")
@@ -21,6 +21,7 @@ import * as crypto from "node:crypto";
21
21
 
22
22
  import {
23
23
  buildNarrowPlan,
24
+ toPosixKey,
24
25
  formatBytes,
25
26
  formatNarrowPlanSummary,
26
27
  } from "./local-tree-diff.js";
@@ -87,6 +88,24 @@ afterEach(() => {
87
88
 
88
89
  // ── Happy-path partitioning ─────────────────────────────────────────────────
89
90
 
91
+ describe("toPosixKey — POSIX key normalization (Windows client regression)", () => {
92
+ // Regression: on a non-POSIX (Windows) client, path.relative() yields
93
+ // "\\"-separated paths. Emitted verbatim as a vault key, `knowledge\books-eoi.md`
94
+ // has no "/", so the server's listing (which splits on "/") renders it flat at
95
+ // the root. The narrow-plan must emit POSIX keys regardless of client OS.
96
+ it("converts a Windows-style nested path to a POSIX key", () => {
97
+ expect(toPosixKey("knowledge\\books-eoi.md")).toBe("knowledge/books-eoi.md");
98
+ expect(toPosixKey("data\\sub\\boots-accounts.json")).toBe(
99
+ "data/sub/boots-accounts.json",
100
+ );
101
+ });
102
+
103
+ it("leaves an already-POSIX key unchanged (idempotent)", () => {
104
+ expect(toPosixKey("meetings/2026/notes.md")).toBe("meetings/2026/notes.md");
105
+ expect(toPosixKey("flat.md")).toBe("flat.md");
106
+ });
107
+ });
108
+
90
109
  describe("buildNarrowPlan — partition by prefix coverage", () => {
91
110
  it("separates files into staying / clean / dirty buckets", () => {
92
111
  // Staying — covered by prospective prefix.
@@ -182,6 +182,22 @@ function emptyPlan(): NarrowPlan {
182
182
  * Uses `lstat` rather than `stat` so a symlink's size doesn't follow the
183
183
  * target chain (matches the share-engine convention).
184
184
  */
185
+ /**
186
+ * Normalize OS-native path separators to POSIX "/" for vault keys.
187
+ *
188
+ * `path.relative()` yields "\\"-separated paths on Windows, but vault S3 keys
189
+ * are always "/"-separated — the server splits keys on "/" to rebuild the tree
190
+ * and the journal + grants endpoint use that same namespace. Emit POSIX keys
191
+ * regardless of client OS so a Windows narrow-plan lines up with the
192
+ * forward-slash keys everywhere else. Mirrors the same normalization on
193
+ * @indigoai-us/hq-cloud's upload path. Converting "\\" explicitly (rather than
194
+ * only path.sep) keeps the result correct — and the regression test meaningful
195
+ * — on a POSIX CI too.
196
+ */
197
+ export function toPosixKey(p: string): string {
198
+ return p.split("\\").join("/");
199
+ }
200
+
185
201
  function walkLocal(
186
202
  dir: string,
187
203
  // Rel-root for `relPath` — the company walk root (`<hqRoot>/companies/<slug>`),
@@ -202,7 +218,7 @@ function walkLocal(
202
218
 
203
219
  for (const entry of entries) {
204
220
  const absPath = path.join(dir, entry.name);
205
- const relPath = path.relative(relRoot, absPath);
221
+ const relPath = toPosixKey(path.relative(relRoot, absPath));
206
222
 
207
223
  if (entry.isSymbolicLink()) {
208
224
  // Record the link as a file-like entry. Don't descend — narrow is
package/src/types.ts CHANGED
@@ -82,6 +82,18 @@ export type PackContributeKey =
82
82
  | 'policies'
83
83
  | 'scripts';
84
84
 
85
+ /**
86
+ * Pack authorship attribution (US-001). OPTIONAL and backwards-compatible —
87
+ * packs published before this field still validate. When present, install can
88
+ * attribute the pack to a creator: `uid` is the HQ person UID, `handle` the
89
+ * creator's marketplace handle, `displayName` the human-readable name.
90
+ */
91
+ export interface PackAuthor {
92
+ uid: string;
93
+ handle: string;
94
+ displayName: string;
95
+ }
96
+
85
97
  export interface PackManifest {
86
98
  name: string; // ^hq-pack-[a-z0-9][a-z0-9-]*$
87
99
  version: string; // semver
@@ -94,4 +106,15 @@ export interface PackManifest {
94
106
  repository?: string;
95
107
  keywords?: string[];
96
108
  conditional?: string; // bash predicate; skip install if exits non-zero
109
+ /**
110
+ * Pack authorship attribution (US-001). Optional — absent on legacy packs.
111
+ */
112
+ author?: PackAuthor;
113
+ /**
114
+ * Declared capabilities the pack touches (US-001), e.g. hooks/scripts/
115
+ * network/fs/secrets. Optional, free-form string entries — surfaced to the
116
+ * user at install time for an at-a-glance trust signal. Reserved here; not
117
+ * yet enforced.
118
+ */
119
+ capabilities?: string[];
97
120
  }
@@ -43,6 +43,47 @@ export async function vaultApiFetch(opts: VaultApiOptions): Promise<Response> {
43
43
  return response;
44
44
  }
45
45
 
46
+ /**
47
+ * Public (NONE-auth) GET against the vault API — no bearer token. The
48
+ * marketplace browse endpoints (`GET /v1/listings`, `GET /v1/listings/{id}`)
49
+ * from US-005 are public so a logged-out user can resolve + download an
50
+ * approved pack. Distinct from `vaultApiFetch`, which always attaches a
51
+ * bearer token.
52
+ */
53
+ export async function vaultApiFetchPublic(opts: {
54
+ path: string;
55
+ query?: Record<string, string>;
56
+ }): Promise<Response> {
57
+ const url = new URL(opts.path, DEFAULT_VAULT_API_URL);
58
+ if (opts.query) {
59
+ for (const [k, v] of Object.entries(opts.query)) {
60
+ url.searchParams.set(k, v);
61
+ }
62
+ }
63
+ const safeUrl = url.search
64
+ ? `${url.origin}${url.pathname}?<redacted>`
65
+ : `${url.origin}${url.pathname}`;
66
+ Sentry.addBreadcrumb({
67
+ category: 'http',
68
+ message: `GET ${opts.path}`,
69
+ level: 'info',
70
+ data: { url: safeUrl, method: 'GET' },
71
+ });
72
+ const response = await fetch(url.toString(), {
73
+ method: 'GET',
74
+ headers: { 'Content-Type': 'application/json' },
75
+ });
76
+ if (!response.ok) {
77
+ Sentry.addBreadcrumb({
78
+ category: 'http',
79
+ message: `GET ${opts.path} → ${response.status}`,
80
+ level: 'warning',
81
+ data: { url: safeUrl, status: response.status },
82
+ });
83
+ }
84
+ return response;
85
+ }
86
+
46
87
  interface MembershipEntry {
47
88
  companyUid: string;
48
89
  role: string;