@optimuslabs/harness-map-staging 1.5.42 → 1.5.44

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.
@@ -90,6 +90,10 @@ export function getQuarantineDir() {
90
90
  export function getSkillBlockProcessesPath() {
91
91
  return join(getRemediationStateDir(), 'skill_block_processes.json');
92
92
  }
93
+ /** The blocked skills the user was already shown the quarantine window for, per server. */
94
+ export function getSkillBlockWindowsShownPath() {
95
+ return join(getRemediationStateDir(), 'skill_block_windows_shown.json');
96
+ }
93
97
  export function getDeferredVscdbApplyPath() {
94
98
  return join(getVscdbStateDir(), DEFERRED_VSCDB_APPLY_BASENAME);
95
99
  }
@@ -173,6 +177,7 @@ const APPROVAL_LISTS = [
173
177
  'skill_blocks',
174
178
  'skill_block_sessions',
175
179
  'skill_block_windows',
180
+ 'skill_block_group_window',
176
181
  'agent_access_windows',
177
182
  ];
178
183
  /** Each approval list from `file` when it names one, else the one on disk; absent ones left out. */
@@ -225,6 +230,10 @@ export function writeSkillBlocks(skill_blocks) {
225
230
  export function writeSkillBlockSessions(skill_block_sessions) {
226
231
  writeApprovalList({ skill_block_sessions });
227
232
  }
233
+ /** Replace only the window for several blocked skills at once, keeping everything else on disk. */
234
+ export function writeSkillBlockGroupWindow(skill_block_group_window) {
235
+ writeApprovalList({ skill_block_group_window });
236
+ }
228
237
  /** Replace only the skill block windows, keeping everything else on disk. */
229
238
  export function writeSkillBlockWindows(skill_block_windows) {
230
239
  writeApprovalList({ skill_block_windows });
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { executeBody } from '../../endpoint_client/http_transport.js';
5
5
  import { parseJsonWithJsoncFallback, parseTomlText, stringifyToml } from '../readers/file_readers.js';
6
6
  import { complianceRunnerDiag, hookRunLog, logRemediationApplyFailure } from './hook_logger.js';
7
- import { atomicWriteJson, getDeferredVscdbApplyPath, getFileCollectionVscdbContractPath, getRemediationInstructionsPath, readRemediationInstructionsFile, writeApprovedTenants, writeUnapprovedEmailDomains, writeAllowedEmailDomains, writeTeamEmailDomains, writeApprovedAgents, writeAgentAccessWindows, writeRemediationInstructionsFile, writeSkillBlockSessions, writeSkillBlockWindows, writeSkillBlocks, } from './management_storage.js';
7
+ import { atomicWriteJson, getDeferredVscdbApplyPath, getFileCollectionVscdbContractPath, getRemediationInstructionsPath, readRemediationInstructionsFile, writeApprovedTenants, writeUnapprovedEmailDomains, writeAllowedEmailDomains, writeTeamEmailDomains, writeApprovedAgents, writeAgentAccessWindows, writeRemediationInstructionsFile, writeSkillBlockSessions, writeSkillBlockGroupWindow, writeSkillBlockWindows, writeSkillBlocks, } from './management_storage.js';
8
8
  import { applySkillBlocks } from './skill_block.js';
9
9
  import { openQuarantineWindows } from './skill_block_sessions.js';
10
10
  import { readStoredAuthKey } from '../auth/auth_key_store.js';
@@ -1695,11 +1695,17 @@ function storeSkillBlockWindows(windows) {
1695
1695
  }
1696
1696
  writeSkillBlockWindows(kept);
1697
1697
  }
1698
+ /** Keep the server's window for several skills at once; null when nothing is blocked. */
1699
+ function storeSkillBlockGroupWindow(words) {
1700
+ if (words === undefined)
1701
+ return;
1702
+ writeSkillBlockGroupWindow(words && typeof words === 'object' && !Array.isArray(words) ? words : null);
1703
+ }
1698
1704
  /**
1699
1705
  * Store the server's skill blocks and make the folders on disk match them. An older server sends
1700
1706
  * no `skill_blocks`: the folders are then left as they are, never unlocked by mistake.
1701
1707
  */
1702
- function enforceSkillBlocks(syncResult) {
1708
+ function enforceSkillBlocks(syncResult, endpointBase) {
1703
1709
  const blocks = syncResult.skill_blocks;
1704
1710
  if (!Array.isArray(blocks))
1705
1711
  return;
@@ -1711,10 +1717,11 @@ function enforceSkillBlocks(syncResult) {
1711
1717
  writeSkillBlocks(entries);
1712
1718
  storeSkillBlockSessions(syncResult.skill_block_sessions);
1713
1719
  storeSkillBlockWindows(syncResult.skill_block_windows);
1720
+ storeSkillBlockGroupWindow(syncResult.skill_block_group_window);
1714
1721
  try {
1715
1722
  const outcome = applySkillBlocks(entries);
1716
1723
  // Tell the user when a skill is quarantined, whether or not a session of theirs loaded it.
1717
- openQuarantineWindows(outcome.quarantined, entries);
1724
+ openQuarantineWindows(outcome.quarantined, entries, endpointBase);
1718
1725
  }
1719
1726
  catch (err) {
1720
1727
  const msg = `skill_block_error: ${errorText(err)}`;
@@ -1857,7 +1864,7 @@ export async function syncRemediations(endpointBase, machineUuid) {
1857
1864
  return;
1858
1865
  applyClearApplyTrackingUuids(syncResult.clear_apply_tracking_uuids);
1859
1866
  storeApprovals(syncResult);
1860
- enforceSkillBlocks(syncResult);
1867
+ enforceSkillBlocks(syncResult, endpointBase);
1861
1868
  if (syncResult.status === 'unchanged') {
1862
1869
  await reconcileUnchanged(endpointBase, machineUuid, remediations, activeUuids);
1863
1870
  return;
@@ -9,8 +9,11 @@
9
9
  * and each file's hash, never its content); the vault entry is `chmod 000`, and an empty `chmod 000`
10
10
  * folder is left at the original path so that no app (Claude Code re-syncing account skills, a
11
11
  * plugin update) can put the skill back. A receipt whose folder is no longer listed is restored.
12
- * A folder is only ever moved when it is a real directory inside the home folder (never the home
13
- * folder itself) holding a SKILL.md, so a bad path cannot move anything that is not a skill.
12
+ * Any folder the inventory reported is quarantined, wherever it is, as long as it is a real
13
+ * directory holding a SKILL.md and never the home folder or a folder above it, so a bad path cannot
14
+ * move anything that is not a skill. The hooks run as the user, so a folder the user cannot move
15
+ * (owned by root) fails and is logged. A listed path that is a symlink quarantines the folder it
16
+ * points to (`quarantinePath`).
14
17
  */
15
18
  import { createHash } from 'node:crypto';
16
19
  import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
@@ -25,6 +28,30 @@ function log(message) {
25
28
  function permissionBits(path) {
26
29
  return lstatSync(path).mode & 0o7777;
27
30
  }
31
+ /**
32
+ * The folder a listed path quarantines: the path itself, or, for a symlink, the folder it points to.
33
+ * The skills CLI (`npx skills add`) installs one copy in `~/.agents/skills/<name>` and links each
34
+ * agent's folder to it (`~/.claude/skills/<name>`), and a link was refused, so a skill the server
35
+ * knew only by its link stayed usable by every agent. Quarantining the folder behind the link closes
36
+ * it for every link and every agent reading it. A chain of more than eight links is left as it is,
37
+ * and refused.
38
+ */
39
+ function quarantinePath(dir) {
40
+ let path = resolve(dir);
41
+ for (let hop = 0; hop < 8; hop++) {
42
+ const next = linkTarget(path);
43
+ if (next === null)
44
+ return path;
45
+ path = next;
46
+ }
47
+ return path;
48
+ }
49
+ /** Where the link at `path` leads, or null when `path` is not a link (missing ones included). */
50
+ function linkTarget(path) {
51
+ if (!exists(path) || !lstatSync(path).isSymbolicLink())
52
+ return null;
53
+ return resolve(dirname(path), readlinkSync(path));
54
+ }
28
55
  /** The vault id of an original path: one path, one entry. */
29
56
  function entryId(dir) {
30
57
  return createHash('sha256').update(resolve(dir)).digest('hex').slice(0, 16);
@@ -111,26 +138,31 @@ function sameFiles(a, b) {
111
138
  }
112
139
  /** When the folder at `dir` was quarantined, or null when it is not. */
113
140
  export function quarantinedAt(dir) {
114
- const receipt = readReceipt(entryId(dir));
141
+ const receipt = readReceipt(entryId(quarantinePath(dir)));
115
142
  return receipt && receipt.status !== 'moving' ? receipt.quarantined_at : null;
116
143
  }
117
144
  /**
118
145
  * The receipt of the skill folder quarantined from `dir`, when the empty folder quarantine left
119
146
  * is still there. The collection reports such a path as quarantined: its skill cannot have changed
120
- * since it was moved, and the server keeps the copy it has.
147
+ * since it was moved, and the server keeps the copy it has. A link to a quarantined folder is
148
+ * reported the same way.
121
149
  */
122
150
  export function quarantineReceiptFor(dir) {
123
- if (!isStub(resolve(dir)))
151
+ const path = quarantinePath(dir);
152
+ if (!isStub(path))
124
153
  return null;
125
- const receipt = readReceipt(entryId(dir));
154
+ const receipt = readReceipt(entryId(path));
126
155
  return receipt && receipt.status !== 'moving' ? receipt : null;
127
156
  }
128
- /** Why `dir` must not be moved, or null when it is a real skill folder inside the home folder. */
157
+ /**
158
+ * Why `dir` must not be moved, or null when it is a real skill folder. Any location the inventory
159
+ * reported can be moved (a project on another drive, a shared folder), except the home folder and
160
+ * the folders above it.
161
+ */
129
162
  export function refusalReason(dir, home = homedir()) {
130
- const root = resolve(home);
131
163
  const target = resolve(dir);
132
- if (!target.startsWith(root + sep))
133
- return 'outside the home folder';
164
+ if (isHomeOrAbove(target, home))
165
+ return 'the home folder or above it';
134
166
  if (!existsSync(target))
135
167
  return 'missing';
136
168
  const stat = lstatSync(target);
@@ -138,12 +170,17 @@ export function refusalReason(dir, home = homedir()) {
138
170
  return 'symlink';
139
171
  if (!stat.isDirectory())
140
172
  return 'not a directory';
141
- if (!realpathSync(target).startsWith(realpathSync(root) + sep))
142
- return 'resolves outside the home folder';
173
+ if (isHomeOrAbove(realpathSync(target), realpathSync(home)))
174
+ return 'the home folder or above it';
143
175
  if (!existsSync(join(target, 'SKILL.md')))
144
176
  return 'no SKILL.md';
145
177
  return null;
146
178
  }
179
+ /** Whether `dir` is the home folder or a folder that holds it (`/Users`, `/`). */
180
+ function isHomeOrAbove(dir, home) {
181
+ const folder = dir.endsWith(sep) ? dir : dir + sep;
182
+ return (resolve(home) + sep).startsWith(folder);
183
+ }
147
184
  /** Move a listed folder into the vault, with its receipt, and leave the empty folder behind. */
148
185
  function moveIn(dir, id, entry, outcome) {
149
186
  const receipt = {
@@ -203,9 +240,9 @@ function keepQuarantined(dir, id, receipt, home, outcome) {
203
240
  makeStub(dir);
204
241
  outcome.requarantined.push(dir);
205
242
  }
206
- /** Quarantine one listed folder, or keep it quarantined. */
243
+ /** Quarantine one listed folder (the one a link points to), or keep it quarantined. */
207
244
  function quarantine(entry, home, outcome) {
208
- const dir = resolve(entry.skill_dir);
245
+ const dir = quarantinePath(entry.skill_dir);
209
246
  const id = entryId(dir);
210
247
  let receipt = readReceipt(id);
211
248
  if (receipt?.status === 'moving') {
@@ -334,7 +371,7 @@ function releaseStateLock(lockPath) {
334
371
  }
335
372
  function applyUnderLock(entries, home, outcome) {
336
373
  releaseInPlaceLocks();
337
- const wanted = new Set(entries.map((entry) => entryId(entry.skill_dir)));
374
+ const wanted = new Set(entries.map((entry) => entryId(quarantinePath(entry.skill_dir))));
338
375
  for (const entry of entries) {
339
376
  try {
340
377
  quarantine(entry, home, outcome);
@@ -11,9 +11,9 @@
11
11
  * of a process that ran a listed one. An unblock takes the sessions off the list.
12
12
  */
13
13
  import { execFileSync } from 'node:child_process';
14
- import { existsSync, readFileSync } from 'node:fs';
14
+ import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
15
15
  import { basename } from 'node:path';
16
- import { atomicWriteJson, getSkillBlockProcessesPath, readRemediationInstructionsFile, } from './management_storage.js';
16
+ import { atomicWriteJson, getSkillBlockProcessesPath, getSkillBlockWindowsShownPath, readRemediationInstructionsFile, } from './management_storage.js';
17
17
  import { launchAgentAccessWindow } from '../../agent_access/window_runner.js';
18
18
  import { quarantinedAt } from './skill_block.js';
19
19
  /**
@@ -162,9 +162,85 @@ function resourceUuidOf(skill) {
162
162
  /** The skills this run already opened the window for, so a prompt that quarantines a skill and is
163
163
  * refused for it opens one window, not two. */
164
164
  const windowsShown = new Set();
165
+ function readWindowsShown() {
166
+ try {
167
+ const path = getSkillBlockWindowsShownPath();
168
+ if (!existsSync(path))
169
+ return {};
170
+ const shown = JSON.parse(readFileSync(path, 'utf8'));
171
+ return shown && typeof shown === 'object' && !Array.isArray(shown) ? shown : {};
172
+ }
173
+ catch {
174
+ return {};
175
+ }
176
+ }
177
+ const lockWait = new Int32Array(new SharedArrayBuffer(4));
178
+ /** Try once to take the lock: 'held', 'busy' (another run holds it), or 'none' (it cannot be made). */
179
+ function takeWindowsLock(lock) {
180
+ try {
181
+ if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > 60_000)
182
+ unlinkSync(lock);
183
+ writeFileSync(lock, '', { flag: 'wx' });
184
+ return 'held';
185
+ }
186
+ catch (err) {
187
+ return err.code === 'EEXIST' ? 'busy' : 'none';
188
+ }
189
+ }
190
+ /**
191
+ * Run `decide` holding the lock on the remembered windows, so the gate and the runner of one prompt
192
+ * decide in turn and the second sees what the first opened. Waits up to two seconds while the other
193
+ * holds it; false, `decide` not run, when it still does. A lock a dead process left goes after a
194
+ * minute. When the lock cannot be made at all (no state folder), `decide` runs without it: a missing
195
+ * folder must not cost the user the window.
196
+ */
197
+ function withWindowsLock(decide) {
198
+ const lock = `${getSkillBlockWindowsShownPath()}.lock`;
199
+ let taken = takeWindowsLock(lock);
200
+ for (let attempt = 1; attempt < 20 && taken === 'busy'; attempt++) {
201
+ Atomics.wait(lockWait, 0, 0, 100);
202
+ taken = takeWindowsLock(lock);
203
+ }
204
+ if (taken === 'busy')
205
+ return false;
206
+ const held = taken === 'held';
207
+ try {
208
+ const state = readWindowsShown();
209
+ const before = JSON.stringify(state);
210
+ decide(state);
211
+ if (JSON.stringify(state) !== before)
212
+ atomicWriteJson(getSkillBlockWindowsShownPath(), state);
213
+ }
214
+ finally {
215
+ try {
216
+ if (held)
217
+ unlinkSync(lock);
218
+ }
219
+ catch {
220
+ // Already gone; the next run takes it again.
221
+ }
222
+ }
223
+ return true;
224
+ }
225
+ /**
226
+ * Open `words` as this prompt's one skill window: 'shown', 'taken' when this prompt (this run, or
227
+ * the other process of the same prompt) already opened one, or 'failed' when it could not open.
228
+ */
229
+ function openForPrompt(words, state) {
230
+ // The prompt's story id when the hook gave one (the gate and the runner share it), else this run.
231
+ const prompt = (process.env.OPTIMUS_STORY_ID || '').trim();
232
+ if (prompt ? state.prompt === prompt : windowsShown.size > 0)
233
+ return 'taken';
234
+ if (!launchAgentAccessWindow('claude', 'skill', words))
235
+ return 'failed';
236
+ if (prompt)
237
+ state.prompt = prompt;
238
+ return 'shown';
239
+ }
165
240
  /**
166
- * Open the window of one blocked skill, by resource uuid, once per run. True when it is open: just
167
- * started, or already started this run; false when the server sent no window for it.
241
+ * Open the window of one blocked skill, by resource uuid, beside a refusal. True when it is open:
242
+ * just started, or already started this run; false when the server sent no window for it, or this
243
+ * prompt already showed another skill's window (the hook then shows its one-line alert).
168
244
  */
169
245
  function openWindowOf(uuid) {
170
246
  if (!uuid)
@@ -174,22 +250,76 @@ function openWindowOf(uuid) {
174
250
  const words = readRemediationInstructionsFile().skill_block_windows?.[uuid];
175
251
  if (!words)
176
252
  return false;
177
- windowsShown.add(uuid);
178
- return launchAgentAccessWindow('claude', 'skill', words);
253
+ let open = false;
254
+ withWindowsLock((state) => {
255
+ open = openForPrompt(words, state) === 'shown';
256
+ });
257
+ if (open)
258
+ windowsShown.add(uuid);
259
+ return open;
179
260
  }
180
261
  /** Open the window beside the block of the skill named `skill` (a stopped session, a typed command). */
181
262
  export function openSkillBlockWindow(skill) {
182
263
  return openWindowOf(resourceUuidOf(skill));
183
264
  }
184
265
  /**
185
- * Open the window for each skill this sync moved into quarantine (`dirs`, the folders it moved), so
186
- * the user hears of it when it happens, even when no session of theirs is known to have loaded it
187
- * (a typed command whose turn made no tool call reaches the server as nothing). One window per
188
- * skill however many of its folders moved.
266
+ * The words for a window opened because the skills in `uuids` were newly blocked (at least one). It
267
+ * lists every skill the server blocks on this machine (`entries`), not only the new ones, so the
268
+ * user sees the whole list each time: the skill's own window when that is one skill, else the
269
+ * server's window for several, its red box listing each by name. An older server sends no window
270
+ * for several: the first new skill's own window then stands for them.
189
271
  */
190
- export function openQuarantineWindows(dirs, entries) {
272
+ function quarantineWords(uuids, entries) {
273
+ const file = readRemediationInstructionsFile();
274
+ const own = file.skill_block_windows ?? {};
275
+ const names = [...new Set(entries.map((e) => e.skill_name))];
276
+ const first = uuids.map((uuid) => own[uuid]).find(Boolean);
277
+ const group = file.skill_block_group_window;
278
+ if (names.length < 2 || !group)
279
+ return first;
280
+ const reason = (group.reason && typeof group.reason === 'object' ? group.reason : {});
281
+ const label = typeof group.group_skill_label === 'string' ? group.group_skill_label : '';
282
+ const findings = [...names].sort().map((name) => ({ severity: 'unknown', label, text: name }));
283
+ return { ...group, reason: { ...reason, findings } };
284
+ }
285
+ /**
286
+ * Open the window for the skills this sync moved into quarantine (`dirs`, the folders it moved), so
287
+ * the user hears of a block when it happens, even when no session of theirs is known to have loaded
288
+ * the skill (a typed command whose turn made no tool call reaches the server as nothing).
289
+ *
290
+ * One window per prompt, listing every skill blocked on the machine (the ones told about before
291
+ * too), and the gate and the runner of the same prompt open at most one between them. A window
292
+ * opens only when a skill is newly blocked, once per skill, by name: a
293
+ * blocked skill gains folders after its block (Claude Desktop copies its skills into a new folder
294
+ * for each session, one skill is in several agents' folders, and each version of a skill is a
295
+ * resource of its own, so `docx` can be several), and each new folder is quarantined by a later
296
+ * sync. The skills told about are remembered per `server` (resource uuids are the server's own,
297
+ * and a machine can sync with more than one), and forgotten once that server no longer blocks
298
+ * them, so a block after an unblock is told again. Skills newly blocked by the second sync of a
299
+ * prompt that already had its window are counted as told.
300
+ */
301
+ export function openQuarantineWindows(dirs, entries, server) {
191
302
  const moved = new Set(dirs);
192
- const uuids = new Set(entries.filter((e) => moved.has(e.skill_dir)).map((e) => e.resource_uuid));
193
- for (const uuid of uuids)
194
- openWindowOf(uuid);
303
+ withWindowsLock((state) => {
304
+ const nameOf = new Map(entries.map((e) => [e.resource_uuid, e.skill_name.toLowerCase()]));
305
+ const servers = state.servers ?? {};
306
+ const shown = Object.fromEntries(Object.entries(servers[server] ?? {}).filter(([uuid]) => nameOf.has(uuid)));
307
+ const toldNames = new Set(Object.keys(shown).map((uuid) => nameOf.get(uuid)));
308
+ const newly = [...new Set(entries.filter((e) => moved.has(e.skill_dir)).map((e) => e.resource_uuid))].filter((uuid) => !shown[uuid]);
309
+ const now = new Date().toISOString();
310
+ const fresh = newly.filter((uuid) => !toldNames.has(nameOf.get(uuid)));
311
+ // Another folder or version of a skill already told about: no window.
312
+ for (const uuid of newly)
313
+ if (!fresh.includes(uuid))
314
+ shown[uuid] = now;
315
+ const words = fresh.length > 0 ? quarantineWords(fresh, entries) : undefined;
316
+ const outcome = words ? openForPrompt(words, state) : 'failed';
317
+ // Told when this prompt's window shows them, or another one already did; not when none opened.
318
+ for (const uuid of outcome === 'failed' ? [] : fresh)
319
+ shown[uuid] = now;
320
+ if (outcome === 'shown')
321
+ fresh.forEach((uuid) => windowsShown.add(uuid));
322
+ servers[server] = shown;
323
+ state.servers = servers;
324
+ });
195
325
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optimuslabs/harness-map-staging",
3
- "version": "1.5.42",
3
+ "version": "1.5.44",
4
4
  "description": "CLI helpers for logging hardware UUIDs and posting startup payloads to Optimus Security.",
5
5
  "type": "module",
6
6
  "bin": {